IntentService 编写本地推送
Android中的Service是用于后台服务的,当应用程序被挂到后台的时候,问了保证应用某些组件仍然可以工作而引入了Service这个概念,那么这里面要强调的是Service不是独立的进程,也不是独立的线程,它是依赖于应用程序的主线程的,也就是说,在更多时候不建议在Service中编写耗时的逻辑和操作,否则会引起ANR。
那么我们当我们编写的耗时逻辑,不得不被service来管理的时候,就需要引入IntentService,IntentService是继承Service的,那么它包含了Service的全部特性,当然也包含service的生命周期,那么与service不同的是,IntentService在执行onCreate操作的时候,内部开了一个线程,去你执行你的耗时操作。
用这个IntentService的时候,那么下面方法首先是要被回调的,可以在这里面做一些操作来区分操作的type,下面的方法是抽象方法,继承intentService时候必须复写的
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_ALERT.equals(action)) {
Bundle extras = intent.getExtras();
if (extras != null) {
TaskEntity taskExtra = ((TaskEntity) extras.getSerializable(TASK_EXTRA));
alert(taskExtra);
return;
}
}
if (ACTION_END_ALERT.equals(action)) {
endAlert();
return;
}
if (ACTION_FIND_TODAY_TASK.equals(action)) {
findTodayTask();
}
if (ACTION_START_ALERT.equals(action)) {
startAlert();
}
}
在每个方法中填写响应的方法,比如查找任务的方法。
private void findTodayTask() {
。
。
。
Context ctx = getApplication();
List<TaskEntity> taskList = Dbutls.queryAll();//查找所有的任务
if (taskList != null && !taskList.isEmpty()) {
// 找到目前要闹铃的任务
TaskEntity noticieTask = null;
TaskEntity nextTask = null;
for (int i = 0; i < taskList.size(); i++) {
TaskEntity tempTask = taskList.get(i);
long tempTaskTime = tempTask.getTimeInMillis();
long delta = tempTaskTime - now.getTime();
if (delta == 0 || (delta < 0 && -delta < 1000)) {
// 任务该提醒(过期1秒的任务)
noticieTask = tempTask;
}
if (delta > 0 && !tempTask.isFinished() && nextTask == null) {
nextTask = tempTask;
}
}
if (noticieTask != null) {
notice(noticieTask); ///显示通知
}
if (nextTask != null) {///下个通知时间
Intent action = new Intent(this,ScheduleAlermService.class);
action.setAction(ACTION_ALERT);
action.putExtra(TASK_EXTRA, nextTask);
alertOperation = PendingIntent.getService(ctx, 1, action,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC, nextTask.getTimeInMillis(),
alertOperation);
} else {
// 今天没有任务
tommory = DateUtil.alignDate(tommory);
// Intent action = AlermServcie_.intent(ctx).findTodayTask().get();
Intent action = new Intent(this,ScheduleAlermService.class);
action.setAction(ACTION_FIND_TODAY_TASK);
operation = PendingIntent.getService(ctx, 1, action, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC, tommory.getTime(), operation);////定时的器
}
} else {
// 如果今天没有任务,则计划一个明天00:00的任务,以计划闹铃
tommory = DateUtil.alignDate(tommory);
Intent action = new Intent(this,ScheduleAlermService.class);
action.setAction(ACTION_FIND_TODAY_TASK);
operation = PendingIntent.getService(ctx, 1, action, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC, tommory.getTime(), operation);
}
}
开启这个服务可以通过广播开启 或者手动开启,如果后台开启的,建议监听开机广播