2012-07-30 36 views
0


在我的情況下,我必須做一個任務,讓我們說在接下來的3小時每5分鐘。哪一個會更好AlarmManger或Timer。在AlarmManger的情況下,我將啓動一個意向服務,它將完成任務,在稍後的一箇中我將使用TimerTask。此外,如何在intentService onHandleIntent中獲得掛起的意圖使用AlarmManager.cancel(pendingIntent)。
使用方法:AlarmManger或使用Timer(scheduleAtFixedRate(task,delay,period))的我自己的服務;

可能的副本,但有不同的情況。 Timer Task VS Alarm Manager usage in Android Service

謝謝。

回答

1

一是成立:

Intent i = new Intent(context.getApplicationContext(), NameOfYourClass.class); 
PendingIntent pi = PendingIntent.getBroadcast(c.getApplicationContext(), 0, i, 0); 
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 5*60*1000, pi); 
// ELAPSED_REALTIME will execute ONLY when phone is awake, to execute always use ELAPSED_REALTIME_WAKEUP 

緊接在該初始設置保存在計數器開始:,恩。 PreferenceManager

最後,在時機成熟時:

Intent i = new Intent(context.getApplicationContext(), NameOfYourClass.class); 
PendingIntent pi = PendingIntent.getBroadcast(context.getApplicationContext(), 0, i, 0); 
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
am.cancel(pi); 
+0

您好感謝它的工作,只有一件事,如果你打算intentservice使用前am.setRepeating使用PendingIntent.getService()而不是getbroadcast。謝謝 – 2012-08-09 12:06:02

相關問題