【问题标题】:Android - open or restart app after clicking push notification using flag activitiesAndroid - 在使用标志活动单击推送通知后打开或重新启动应用程序
【发布时间】:2023-03-23 16:34:01
【问题描述】:

我在 Android 中使用推送通知。当我收到推送通知时,如果应用程序仍在运行,我想打开它,否则它应该打开它的一个新实例。

我正在使用

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 
    Intent.FLAG_ACTIVITY_CLEAR_TOP | 
    Intent.FLAG_ACTIVITY_SINGLE_TOP | 
    Intent.FLAG_ACTIVITY_NEW_TASK);

但是当我现在收到推送通知并单击它时,什么也没有发生。

我怎样才能通过使用 flagIntents 来实现这一点?

【问题讨论】:

    标签: java android push-notification google-cloud-messaging


    【解决方案1】:

    您需要在Intent 上设置 Intent 标志。您在调用中指定它们以获得PendingIntent。试试这个:

    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
        Intent.FLAG_ACTIVITY_SINGLE_TOP | 
        Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
        notificationIntent, 0);
    

    【讨论】:

    • 是的,这行得通。 Ecpet 现在我有另一个问题。有没有办法执行我在 onCreate() 中的代码,因为它包含推送通知必须执行的相同代码。现在 onCreate 没有被调用,因此代码没有被执行。
    • 如果不设置标志Intent.FLAG_ACTIVITY_SINGLE_TOP,那么Activity的当前实例将被销毁并创建一个新实例(从而调用onCreate())。
    • 这对我不起作用...您必须在清单中为此活动设置特定的启动模式吗?
    • @Tooroop 不,你不知道。什么不工作?你能说得更具体点吗?
    • 看来我解决了。如果我同时设置 Intent.Intent.FLAG_ACTIVITY_SINGLE_TOP 或 launchMode="singleTop" 甚至 btoh,我的 onNewIntent() 方法将不会被调用。我补充说: Intent intent = new Intent(this, MainActivity.class);意图.addFlags(意图.FLAG_ACTIVITY_CLEAR_TOP);在清单中我设置了launchMode =“singleTask”。现在它按预期工作了
    【解决方案2】:

    在您的 Android Mainfest 文件中设置以下内容

    android:noHistory="true"
     android:launchMode = "singleTop"
    

    【讨论】:

    • 为什么是android:noHistory="true"android:launchMode = "singleTop"
    【解决方案3】:

    在我的情况下,每次单击推送通知时都会重新启动正在运行的应用程序。但我不想重新启动应用程序。

    PendingIntent 中,我有一个名为 Activity2 的所需 Activity1 的意图。这些行中有一个错误:

    val intent = Intent(context, Activity2::class.java)
    // Remove this line:
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
    context.startActivity(intent)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多