2016-03-07 91 views
4

所以我遇到了AlarmManager的問題。我試圖每隔2分鐘運行一段代碼,這在手機醒來時可以正常工作,但不是在設備進入睡眠狀態時 - 在睡眠期間,間隔完全相隔5分鐘。Android AlarmManager在電話屏幕關閉時默認爲5分鐘

由於我所需的間隔時間爲2分鐘,因此我的目標間隔大約爲250%,這對於我的特定應用是不可接受的。

我知道API 19中的更改,並且遵循了在我的BroadcastReceiver中使用setExact()重新安排警報的建議。代碼如下:

的代碼用於觸發廣播接收器:

Intent intent = new Intent(this, AlarmReceiver.class); 
    final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); 

    mAlarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); 
    mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 3000, pendingIntent); 

而且這個代碼是在我的廣播接收器,其重新安排了警鐘:

@Override 
public void onReceive(Context context, Intent intent) { 
    Toast.makeText(context, "AlarmService Triggered.", Toast.LENGTH_SHORT).show(); 
    Log.d(this.getClass().getSimpleName(), "Service triggered"); 

    Intent newIntent = new Intent(context, this.getClass()); 
    mPendingIntent = PendingIntent.getBroadcast(context, 0, newIntent, 0); 

    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
    alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 120000, mPendingIntent); 
} 

沒有人有建議如何我可以解決這個問題?令人非常沮喪的是,AlarmManager完全無視我希望在某個確切時間發生警報的情況。是否有任何替代方案可以讓我按照需要以2分鐘的間隔安排代碼?

設備:三星Galaxy S6,OS 5.1.1

回答

3

由於@Francesc建議,它最終被三星設備。嘗試在另一部手機上,現在它完美無瑕。

讓這給你一個教訓 - 不要買三星,他們做奇怪的東西,哈哈。

1

更換ELAPSED_REALTIME_WAKEUP與RTC_WAKEUP。

我這是怎麼安排的報警:

 mTargetTime = System.currentTimeMillis() + timeout * 1000L; 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mTargetTime, mPendingIntent); 
     } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
      alarmManager.setExact(AlarmManager.RTC_WAKEUP, mTargetTime, mPendingIntent); 
     } else { 
      alarmManager.set(AlarmManager.RTC_WAKEUP, mTargetTime, mPendingIntent); 
     } 
+0

沒有什麼區別,已經試過了。 – privatestaticint

+0

您正在使用3000進行報警:SystemClock.elapsedRealtime()+ 3000. 2分鐘爲120000. – Francesc

+0

最初的3000毫秒延遲僅觸發第一個報警,然後所有報警在120000毫秒延遲時間內重新安排在BroadcastReceiver中。我會嘗試你的上面的塊,看看它是否適合我。 – privatestaticint