簡體   English   中英

AlarmManager 在指定時間后未喚醒 BroadcastReceiver

[英]AlarmManager not waking up a BroadcastReceiver after the specified time

我有完美的通知。 這些通知由服務創建。 當我試圖在用戶沒有點擊它 3 分鍾時關閉通知時。 我在這里嘗試了 Karakuri 的解決方案https://stackoverflow.com/a/23874764 ,但什么也沒發生。 警報不起作用,廣播接收器沒有被調用。

服務中的警報管理器 class:

notificationManager.notify(notificationId, n);
//set up alarm
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(context, MyReceiver.class);                                        intent.setAction("com.example.example.action.CANCEL_NOTIFICATION");
intent.putExtra("notification_id", notificationId);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP,180000,pi);

廣播接收器onReceive方法:

public void onReceive(Context context, Intent intent) {
// do something
final String action = intent.getAction();
Log.d("Reciver","onReceive lunched");
if ("com.example.example.action.CANCEL_NOTIFICATION".equals(action)) {
int id = intent.getIntExtra("notification_id", -1);
if (id != -1) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
Log.d("Noti "+id," canceled ");
}}}

我之前沒有和警報管理器打過交道。 我研究了知道原因,但我沒有找到,希望有人能幫助我解決這個問題

如果您需要在請求的時間准確觸發,您應該使用alarmManager.setExactAndAllowWhileIdle方法而不是alarmManager.set

另外,您設置的時間錯誤。 如果您希望警報從當前時刻開始 3 分鍾觸發,則它必須是System.currentTimeMillis() + 180000

最后,檢查您是否添加了SET_ALARM權限並在您的AndroidManifest.xml中聲明了您的廣播接收器。

您可以使用 Handler,它比使用 Alarm Manager 更容易。 由於您在 Service 中工作,因此請使用 Looper

這里已經接受的答案將指導您:

幾秒鍾后清除通知

在服務內部使用 Handler

我希望我能幫上忙!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM