我有一个应用程序,它反过来运行前台服务。应用程序有一个启动/停止按钮作为其通知的一部分,可以猜到它启动和停止前台服务。单击启动按钮后,将触发一个挂起的意向。
考虑以下场景:
应用程序已被销毁[从最近的项目列表中删除],但通知仍然可见。即使应用程序被破坏,我也可以启动和停止前台服务,因为点击通知按钮会触发挂起意图(进而调用广播接收器(。但是,我观察到的是,一两天后,单击通知上的按钮后,不会触发挂起的意图(即前台服务不会启动(。这就引出了一个问题,在包含的应用程序被破坏后,未决意图是否有生命周期?还是我错过了别的东西?
我的意向电话:
Intent notificationBroadcastIntent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent playIntent = PendingIntent.getBroadcast(this, MY_REQUEST_CODE,
notificationBroadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
未决意图调用的广播接收器(反过来启动前台服务(:
@Override
public void onReceive(Context context, Intent intent) {
Log.i(MyBroadcastReceiver.class.getSimpleName(), "MyBroadcastReceiver called to update service notification");
if (isMyForegroundServiceRunning(MyForegroundService.class, context)) {
Intent stopIntent = new Intent(context, MyForegroundService.class);
stopIntent.setAction(STOP_SERVICE_ACTION);
context.startService(stopIntent);
} else {
Intent startIntent = new Intent(context, MyForegroundService.class);
startIntent.setAction(START_SERVICE_ACTION);
context.startService(startIntent);
}
}
PendingIntent
s不会过期。但是,它们不是持久性的,在设备重新启动后将无法存活。
要查看PendingIntent
是否仍然存在,可以使用以下adb命令:
adb shell dumpsys activity intents
这列出了系统中的所有PendingIntent
。您也可以使用查看通知
adb shell dumpsys notification
这将显示所有Notification
,包括为它们设置的PendingIntent
。