![](/img/trans.png)
[英]setRepeating of AlarmManager is only triggering for the first time and not repeating
[英]AlarmManager triggers only the first time even when set to repeating
我現在試圖解決這個問題。
在我的活動中,我將警報管理器設置為每2分鍾觸發一次(用於測試)並通過接收器調用服務。 該服務應該進行網絡呼叫等。
我的問題是AlarmManager會第一次正確觸發,但永遠不會再次觸發。 我錯過了什么?
在我的活動中,我這樣做-
//Register an alarm manager
//If no alarm is set
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
if(!defaultSharedPref.getBoolean("isAlarmSet",false)){
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
R.string.interval,
pendingIntent);
editor = defaultSharedPref.edit();
editor.putBoolean("isAlarmSet",true);
editor.commit();
}
在我的清單上:
<receiver android:process=":remote" android:name=".receiver.AlarmReceiver" />
<service android:name=".service.AlarmService"/>
我的接收器:-
public class AlarmReceiver extends WakefulBroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AlarmService.class);
startWakefulService(context,i);
}
}
我什至嘗試了“ setRepeating”,但是沒有運氣。 它仍然僅觸發一次。 有人可以指出我錯過了什么嗎?
提前致謝。
作為重復計時器的間隔,您要指定資源ID-R.string.interval。 這沒有任何意義,但由於是整數,因此可以編譯。 如果希望將間隔作為資源使用,則最好使用整數資源,但是最關鍵的更改是傳遞資源的實際值而不是資源id 。 因此,請使用Resources.getInteger或getString。
這應該可行,但是我鼓勵您完全不要使用字符串資源:
manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
Integer.parseInt(getResources().getString(R.string.interval)),
pendingIntent);`
在實踐中看不到任何觸發警報的原因是資源ID是非常大的整數,通常在0x8000000范圍內,因此您可以有效地設置間隔非常長的周期性警報。 如果您等待一個月左右,則會觸發警報。 :-)
如果您想以更靈活的方式安排作業,我建議您使用該庫為您摘要使用的計划程序: https : //github.com/evernote/android-job
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.