【发布时间】:2015-01-04 19:34:03
【问题描述】:
在我的应用程序关闭后的一段时间,我已经从 SO 关注 some tutorials,通过向我的自定义 BroadcastReceiver 实现广播,使用 AlertManager 生成本地通知。效果很好,我可以在设备的通知区域看到通知。
但是,它仅在应用的主要活动暂停时才有效。如果应用程序停止(通过设置->应用程序),没有通知,广播接收器永远不会被调用。我的印象是 AlertManager 在某些操作系统服务中注册我的通知请求 - 与我的应用程序无关,这就是重点,有某种通知,用户可以通过它重新启动我的应用程序。我正在测试 Android 4.2.1 BTW。有没有可能我只是做错了什么,实际上有一种方法可以让 AlertManager 成功广播某些内容?
这是我的 AlertManager 代码,从我的主要活动的 onPause 调用(设置为 10 秒,仅用于测试)。 'ctx' 是主要活动
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(ctx, MyAlarmReceiver.class);
intent.putExtra("alarm_message", "hey, wake up this app!");
// note: 192837 is just some test ID:
PendingIntent sender = PendingIntent.getBroadcast(ctx, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Get the AlarmManager service
AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
这里是 MyAlarmReceiver.onReceive(context, intent):
try {
Bundle bundle = intent.getExtras();
String message = bundle.getString("alarm_message");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Title!!!")
.setContentText(message);
Intent resultIntent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(context, 192838, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(123423, mBuilder.build());
} catch (Exception e) {
Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
【问题讨论】:
标签: android android-intent notifications broadcastreceiver