Alarm Manager元件用來排程,當時間到時系統會廣播註冊指定的Intent啟動目標程式,就算目標程式並未在執行中也一樣。若是裝置在睡眠中,則依參數而定,註冊的鬧鐘會保留或喚醒裝置。當系統關閉並rebooted時,會清除鬧鐘的設定。當廣播接受端執行onReceive() 時,Alarm Manager會保持CPU清醒直到處理結束。裝置有可能一旦執行完onReceive()時,立刻進入昏睡(睡眠不足:),所以不要在onReceive()中呼叫非同步動作的函數。若一定要作時,請自行處理wake lock policy(鎖定清醒)。
Intent intent=new Intent (getBaseContext(),CallAlarm.class); PendingIntent sender=PendingIntent.getBroadcast(getBaseContext(),0,intent,0); AlarmManager am ; am = (AlarmManager)getSystemService(ALARM_SERVICE); long cl = SystemClock.elapsedRealtime(); //連續式 am.setRepeating(AlarmManager.ELAPSED_REALTIME, cl, 5*1000, sender) ; //單次 am.set(AlarmManager.ELAPSED_REALTIME, cl + 5*1000, sender); public class CallAlarm extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent arg1) { int n =arg1.getIntExtra(Intent.EXTRA_ALARM_COUNT,0); Toast.makeText(arg0,"ALARM RECEIVE="+n,Toast.LENGTH_SHORT).show(); } } 接收器程式記得在AndroidManifest.xml中註冊, <receiver android:name=".CallAlarm" android:process=":remote" />
沒有留言:
張貼留言