以下是发生的情况:
- 我已经注册了一个网络状态更改侦听器
-
当控制进入网络状态更改时,我会在5分钟后创建一个警报,以显示通知:
Intent alarmIntent = new Intent(context, NotificationReceiver.class); alarmIntent.putExtra(EXTRA_MODE, MODE); alarmIntent.setAction(NotificationReceiver.INTENT_ACTION); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, pendingIntent);
此处delay
=5000
- 然后在NotificationReceiver中,我显示一个通知
- 我在清单中定义了通知接收者,如下所示:https://gist.github.com/Sheikh-Aman/ee40ec35c52ed9d66d6d(它没有出现在这里,不知道为什么)
现在,当网络状态发生变化时,我确实会收到通知,并且我可以设置警报。当警报响起时,我大多数时候都没有收到NotificationReceiver
的onReceive
中的控制,主要是当应用程序不在前台,也不在最近的任务列表中时。
你知道为什么会发生这种事吗?或者我在这里做错了什么?
更新:我可以在运行5.x的Nexus 5上复制它
复制方式如下:
- 安装应用程序
- 不要打开它
- 更改网络状态且未收到通知
是因为该应用程序必须至少启动一次才能使其警报和广播接收器工作吗?
最终更新::事实证明,除非应用程序在安装后至少启动一次,否则它将保持在Stopped
状态,这相当于从设置中强制关闭应用程序,在这种状态下,不会发送广播。这意味着在这种情况下,我遇到了平台限制。
我看到你的代码了。这里面有一些变化。试着使用这个
// To get system time.
Long systemTime = SystemClock.elapsedRealtime();
Intent alarmIntent = new Intent(context, NotificationReceiver.class);
alarmIntent.putExtra(EXTRA_MODE, MODE);
//set request code doffirent all the time request=102
// Alarm is delayed after the delay of 5 sec
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 102, alarmIntent, 0);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, systemTime + 5*60*1000, pendingIntent);
事实证明,除非应用程序在安装后至少启动一次,否则它将保持在Stopped
状态,这相当于从设置中强制关闭应用程序,在这种状态下,不会传递任何广播。这意味着在这种情况下,我遇到了平台限制。