2016-01-18 32 views
3

我正在使用警報管理器每隔40秒觸發一次意向服務。下面的代碼是我如何觸發警報並啓動服務。我知道警報並非總是在40秒後觸發,而且可能會有所不同。AlarmManager在5分鐘後觸發,但未在所需時間觸發

但是我得到了一個報警變化很大的情況,並且每隔5分鐘就會持續觸發一次。

啓動報警:

Intent alarmIntent = new Intent(context, AlarmReceiver.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0); 
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
long interval = 40000; 
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent); 

報警接收機:

@Override 
public void onReceive(Context arg0, Intent arg1) 
{ 
    globalVariables.DebugLogging("IsSignedIn: "+GlobalVariables.IsSignedIn+" -DownloadServiceCanStart:- "+GlobalVariables.DownloadServiceCanStart); 
    if(GlobalVariables.IsSignedIn) 
    { 
      if (GlobalVariables.DownloadServiceCanStart) 
      { 
       GlobalVariables.DownloadServiceCanStart=false; 
       Intent intent = new Intent(arg0, DownloadService.class); 
       context.startService(intent); 
      } 
    } 
} 
+0

任何人都可以幫助我? –

+0

這是一個Android錯誤。我假設你有一個三星設備。很多這是製造商依賴和三星似乎喜歡使用5分鐘的重複。請參閱https://code.google.com/p/android/issues/detail?id=211988&thanks=211988&ts=1464886635 –

回答

1

AlarmManager不是很精確。

隨着官方文檔狀態:

注:與API開始19(奇巧)警報傳遞不精確:操作系統 會以最小化喚醒和電池使用SHIFT報警。有 是新的API來支持需要嚴格交付 保證的應用程序;請參閱setWindow(int,long,long,PendingIntent)和setExact(int,long,PendingIntent)。其中 targetSdkVersion早於API 19的應用程序將繼續看到 之前的行爲,在該行爲中, 請求時所有報警均準確傳送。

還有一個60秒的最小間隔。所以你的40秒間隔將會擴大到60秒。

如果你想每40秒運行完全相同的東西,你可以調查這個答案: https://stackoverflow.com/a/9539579/503508

+0

好的,謝謝生病看看,我知道它不準確,但它去了5分鐘,然後精確地每5我發現奇怪的分鐘。 –

+0

這是一個錯誤。請參閱https://code.google.com/p/android/issues/detail?id=211988&thanks=211988&ts=1464886635 –

+0

此外,官方文檔是錯誤的。即使您定位API <19,但在大多數Android 5和所有Android 6設備上,您都無法獲得指定的行爲。而且它非常適合製造商。 –