3

我知道這個問題之前被問過,但我沒有得到任何答案,我想創建一個意圖的服務,始終運行一個線程,但是當我走出從應用程序我的服務停止,然後線程也停止。我需要創造一些東西來每隔幾分鐘喚醒一次服務。或者是爲了防止應用程序被殺或關閉而終止服務。如何喚醒我的意圖服務,每5分鐘

這就是我開始我的服務

Intent intent= new Intent(Intent.ACTION_SYNC,null,this,IntentServ.class); 
startService(intent); 
+1

使用普通服務代替IntentService – Chandrakanth

+1

AFAIK您可以使用一個wakefulbroadcast與一個處理程序... alarmmanager也會幫助您在這裏,,,,你試過 – Ranjit

+0

正常服務工作一段時間,而意圖服務工作了很多時間,然後意向服務是最有用的 – Malo

回答

6

爲此,您可以使用可以每1小時開始一次服務的AlarmManager。例如:

AlarmManager mgr = (AlarmManager) context 
       .getSystemService(Context.ALARM_SERVICE); 
Intent notificationIntent = new Intent(context, 
       UpdateService.class); 
PendingIntent pendingIntent=PendingIntent.getService(context, requestCode, Intent.parseIntent(), 0); 
    mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, 
     System.currentTimeMillis(), AlarmManager.INTERVAL_HOUR, pendingIntent); 
+0

謝謝我創建鬧鐘管理器,除了正常的服務及其工作之外,現在我試圖阻止設備進入睡眠狀態,您認爲警報管理器不會睡覺設備? – Malo

+2

AlarmManager不會阻止設備進入休眠狀態,但如果您希望在觸發警報時喚醒設備,則可以在註冊時使用AlarmManager.RTC_WAKEUP,否則可以使用AlarmManager.RTC。 http://developer.android.com/reference/android/app/AlarmManager.html – Kartheek

+0

爲什麼不提倡'START_STICKY'並節省資源? – Kiran

1

使用正常Serviceandroid.app.AlarmManager

不需要使用WakefulBroadcastReceiver

1

AlarmManagerPendingIntent你在這種情況下所需要的。 按照下面的例子:

AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); 

/* ---創建掛起的意圖,這將在執行時喚醒--- */

PendingIntent operation = getUpdatePolicyOperation(); 
am.set(AlarmManager.RTC, alarmTime, operation); // alarm time is millisecond time in milliseconds that the alarm should go off, using the appropriate clock (depending on the alarm type). 

您可以在AlarmManager閱讀更多關於報警模式在Here或在Here

希望它的幫助。

+0

非常感謝你,我希望我可以接受更多回答:) – Malo

+0

即時通訊設法防止設備進入睡眠狀態,您是否認爲鬧鐘管理器不會睡眠設備? – Malo