【发布时间】:2020-09-29 16:11:26
【问题描述】:
我有一个应用程序,它又运行一个前台服务。该应用程序有一个启动/停止按钮作为其通知的一部分,可以猜测它启动和停止前台服务。单击开始按钮后,将触发 Pending Intent。
考虑以下场景:
应用程序已被销毁[从最近的项目列表中删除],但通知仍然可见。 即使应用程序已被销毁,我也能够启动和停止前台服务,因为单击通知按钮会触发待处理意图(进而调用广播接收器)。 但是,我观察到的是,一两天后,单击通知上的按钮后,未触发未触发的意图(即前台服务未启动)。这就引出了一个问题,待处理的意图在包含的应用程序被销毁后是否还有生命周期?还是我在这里遗漏了什么?
我的未决意图调用:
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);
}
}
【问题讨论】:
标签: android broadcastreceiver android-pendingintent foreground-service