从 IntentService 启动 Activity 在 Android 12 上无法工作。

4

简单背景:我已将最新的targetSdkVersion更新为最新的Android 31。

我有一个服务类,在从通知托盘中点击通知后执行,它包含以下代码:

public class NotificationClickListener extends IntentService {

    @Override
    protected void onHandleIntent(Intent intent) {
        Intent myIntentFromPendingIntent = intent;
        //insert some necessary code

        myIntentFromPendingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(myIntentFromPendingIntent); //this line here gets executed but the application or the activity wasn't opened after this line
    }

收到消息后,可以按照以下代码创建PendingIntent。
    PendingIntent contentIntent = PendingIntent.getService(appContext, 0, intent, PendingIntent.FLAG_IMMUTABLE);
    mNotificationManager.notify(0, myNotification);

我没有得到任何错误日志或相关的跟踪日志,我看到的唯一日志是

    D/skia: --- Failed to create image decoder with message 'unimplemented'

我浏览了一些文档,并偶然发现从后台启动活动的限制,其中列出了一些例外情况之一是当“应用程序在前台任务的返回堆栈中具有活动”时。因此,我希望我的活动将被启动(假设我的应用程序在后台暂停)。

有人能帮我找到问题所在吗?是否可能仍然使用IntentService修复此问题?

或者现在是否需要使用WorkManager进行迁移?如果是这样,请您留下一个好的参考链接。

非常感谢。

1个回答

1
我原本期望我的活动会启动(考虑到我的应用被暂停在后台)。
顺便提一下,似乎它不符合你所引用的规则: "该应用程序具有在前台任务堆栈中的活动。"(已加重音) - 你的应用程序在后台而不是前台。
我有一个服务类,在通知托盘中点击通知后执行该类,其中包含以下代码:
让您的通知直接启动活动。一旦您的目标SdkVersion达到31或更高版本,像这样的"蹦床"就被禁止

1
让我尝试直接启动该活动,应该像这样直接使用PendingIntent contentIntent = PendingIntent.getService(appContext, 0, intentAsMyExpectedActivity, PendingIntent.FLAG_IMMUTABLE);,对吗? - Zerosero
1
@Zerosero:应该是getActivity()而不是getService(),但除此之外看起来很好。 - CommonsWare
啊,非常感谢!现在没问题了 :D - Zerosero
@CommonsWare 关于通知跳板 - 当推送导致外部应用程序/活动(例如:导致 Google Play 的推送)时,如何进行推送点击分析? - Kocus
@Kocus:我很惊讶你提出的技巧居然有效,但我不会抱怨!真是个好发现! - CommonsWare
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接