Android ApiDemos示例解析(20):App->Alarm->Alarm Service

Alarm Service和Alarm Controller 例子非常類似,隻是Alarm Service是用來Schedule一個Service,而前面的例子是來Schedule一個Broadcast。

前面說過PendingIntent ,可以來描述一個Activity ,Broadcast,或是一個Service。本例是Schedule一個Alarm事件來啟動一個Service。這通常用於來執行一個較費時的任務。

關於如果編寫一個Service將在後面的有專門的例子來說明,隻裡不詳述。隻要知道AlarmService_Service是一個Service就行瞭。

下面的代碼用來Schedule一個多次Alarm事件來啟動AlarmService_Service

[java] 
private PendingIntent mAlarmSender; 
 … 
// Create an IntentSender that will launch our service, to be scheduled  
 // with the alarm manager.  
mAlarmSender = PendingIntent.getService(AlarmService.this, 
 0, new Intent(AlarmService.this, AlarmService_Service.class), 0); 
… 
// We want the alarm to go off 30 seconds from now.  
long firstTime = SystemClock.elapsedRealtime(); 
  
// Schedule the alarm!  
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); 
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
 firstTime, 30*1000, mAlarmSender); 
private PendingIntent mAlarmSender;
 …
// Create an IntentSender that will launch our service, to be scheduled
 // with the alarm manager.
mAlarmSender = PendingIntent.getService(AlarmService.this,
 0, new Intent(AlarmService.this, AlarmService_Service.class), 0);

// We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime();
 
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
 firstTime, 30*1000, mAlarmSender);

取消這個Alarm事件:

 

[java] 
// And cancel the alarm.  
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); 
am.cancel(mAlarmSender); 
// And cancel the alarm.
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.cancel(mAlarmSender);

 


作者:mapdigit
 

發佈留言