@Override public void onClick(View v) { // TODO Auto-generated method stub int id = v.getId(); switch(id){ case R.id.button1: ServiceUtil.invokeTimerPOIService(mContext); break; case R.id.button2: ServiceUtil.cancleAlarmManager(mContext); break; }类ServiceUtil.java
public static void invokeTimerPOIService(Context context){ Log.i("ServiceUtil-AlarmManager", "invokeTimerPOIService wac called.." ); PendingIntent alarmSender = null; Intent startIntent = new Intent(context, UploadPOIService.class); startIntent.setAction(Constants.POI_SERVICE_ACTION); try { alarmSender = PendingIntent.getService(context, 0, startIntent, PendingIntent.FLAG_UPDATE_CURRENT); } catch (Exception e) { Log.i("ServiceUtil-AlarmManager", "failed to start " + e.toString()); } AlarmManager am = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE); am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), Constants.ELAPSED_TIME, alarmSender); } public static void cancleAlarmManager(Context context){ Log.i("ServiceUtil-AlarmManager", "cancleAlarmManager to start "); Intent intent = new Intent(context,UploadPOIService.class); intent.setAction(Constants.POI_SERVICE_ACTION); PendingIntent pendingIntent=PendingIntent.getService(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarm=(AlarmManager)context.getSystemService(Activity.ALARM_SERVICE); alarm.cancel(pendingIntent); }在类UploadPOIService,是一个service,使用Thread.sleep模拟网络HTTP请求。
@Override public void run() { // TODO Auto-generated method stub try { Log.i(TAG, "UploadPOIService beign to upload POI to server "); Thread.sleep(5*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } stopSelf(); }类BootBroadcastReceiver,注册一个静态Broadcast,接收系统级的ACTION_BOOT_COMPLETED事件,用于开机set alarm。
@Override public void onReceive(Context context, Intent intent) { mContext = context; if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED) || intent.getAction().equals(Intent.ACTION_USER_PRESENT)) { Log.i("BootBroadcastReceiver", "BroadcastReceiver onReceive here.... "); Handler handler = new Handler(Looper.getMainLooper()); //after reboot the device,about 2 minutes later,upload the POI info to server handler.postDelayed(new Runnable() { @Override public void run() { if(!ServiceUtil.isServiceRunning(mContext,Constants.POI_SERVICE)){ ServiceUtil.invokeTimerPOIService(mContext); } } }, Constants.BROADCAST_ELAPSED_TIME_DELAY); } }运行后,针对question 1和question 3进行测试。从打印的log分析问题。执行步奏:在控制台,使用adb kill命令杀死进程,观察先前设置的AlarmManager是否还有效果?log如下:
原文:http://blog.csdn.net/coder80/article/details/40742877