Android ApiDemos樣本解析(20):App->Alarm->Alarm Ser

來源:互聯網
上載者:User

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
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.