NotificationService类
public class NotificationService extends Service {
private Notification notification;
private PendingIntent pit;
private NotificationManager notificationManager;
public NotificationService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Intent it = new Intent(this, MainActivity.class);
// it.putExtra("NotificationService","SUCCESS");
pit = PendingIntent.getActivity(this, 0, it, 0);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder mBuilder=new Notification.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_launcher_background)//设置小图标
.setContentTitle("预警信息")//标题
.setContentText("1111")
.setWhen(System.currentTimeMillis()) //设置通知时间
.setAutoCancel(true) //设置点击后取消Notification
.setContentIntent(pit);
notification = mBuilder.build();
notificationManager.notify(1,notification);
}
}
MainActivity类
public class MainActivity extends AppCompatActivity {
private AlarmManager manager;//实现定时
private PendingIntent pi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager= (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, NotificationService.class);
pi = PendingIntent.getService(this, 0, intent, 0);
// 设置AlarmManager启动与时间间隔(低于一分钟会以一分钟计算)
manager.setRepeating(AlarmManager.RTC_WAKEUP, AlarmManager.RTC,300000L, pi);
}
}