【问题标题】:Does a Pending Intent have a lifetime?Pending Intent 有生命周期吗?
【发布时间】: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


    【解决方案1】:

    PendingIntents 不会过期。但是,它们不是持久的,并且不会在设备重新启动后继续存在。

    要查看PendingIntent是否还存在,可以使用下面的adb命令:

    adb shell dumpsys activity intents

    这会列出系统中的所有PendingIntents。您还可以使用以下方式查看通知:

    adb shell dumpsys notification

    这将显示所有Notifications,包括为它们设置的PendingIntents。

    【讨论】:

    • 感谢您的回复。我确实想了解一件事。如果应用程序已经被销毁,只剩下前台服务通知,通知有一个按钮来启动和停止服务(挂起的意图触发服务的启动),通知可以触发挂起的时间是否有限制意图?
    • 没有。没有时间限制。你的问题是别的。您在哪些设备上看到过这种行为?
    • 我在三星手机上观察到了这一点。如果应用程序已经被销毁并且通知上的按钮处于停止状态(即前台服务未运行)并且我没有更改通知上的状态让我们说一天,然后尝试启动前台服务从通知(这是一个未决的意图),我看到前台服务没有启动。我尝试过从 adb 调试,但没有发现异常。
    • 难以置信。您是否在未过滤的情况下检查了 logcat?有时过滤 logcat 会导致您错过一些重要的事情。你在其他设备上试过吗?
    • 在考虑了问题发生时的所有日志后,我发现了这一点。 BroadcastQueue:不允许后台执行:接收 Intent { act=android.net.conn.DATA_ACTIVITY_CHANGE flg=0x10 (has extras) } 到 com.oneplus.security/.network.trafficalarm.TrafficUsageAlarmReceiver。当对前台服务的调用不使用 startForegroundService() 时会出现这种异常。我已经在错过上述电话的任何地方进行了必要的更改。如果这解决了问题,将更新您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多