Android 定时任务设置

jopen 11年前

产品客户端需要增加提醒功能,类似闹钟,这边实现方式就是AlarmManager+广播,设置两个广播,一个用来接收执行任务的;一个用来实现开机启动,实现后台服务。代码如下:

关机重启执行接收广播,执行重新计算任务时间的service

public class BootReceiver extends BroadcastReceiver{  private static final String ACTION="android.intent.action.BOOT_COMPLETED";      public void onReceive(Context context, Intent intent) {                        if (intent.getAction().equals(ACTION)){                  Intent it = new Intent(Intent.ACTION_RUN);                   it.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);                   it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                      it.setClass(context, ServiceSetTime.class);                         context.startService(it);                                         }  }  }

执行任务的线程:

 public void onReceive(Context context, Intent intent) {                Intent i= new Intent();                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                i.setClass(context, TService.class);                context.startService(i);         }    }

当然,如果初次进入程序时也得设置下时间,设置任务时间与闹钟的机制一样