【问题标题】:Android Notification open currently running app instead of creating a new process?Android通知打开当前正在运行的应用程序而不是创建一个新进程?
【发布时间】:2015-10-30 11:18:57
【问题描述】:

我收到带有自定义 Uri 方案的推送通知:myapp://main

在我的onReceive 我创建了一个通知:

public void createNotification(Context context, String title, String message, String summary, Uri uri) {
    Notification.Builder notification = new Notification.Builder(context)
            .setContentTitle(title)
            .setContentText(message)
            .setSmallIcon(R.drawable.ic_launcher)
            .setDefaults(Notification.DEFAULT_LIGHTS)
            .setAutoCancel(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && summary != null)
        notification.setSubText(summary);


    Intent intent = new Intent("android.intent.action.VIEW", uri);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    notification.setContentIntent(pendingIntent);

    Notification noti;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        noti = notification.build();
    else
        noti = notification.getNotification();

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, noti);
}

当我点击该通知时,它会打开一个新的 Activity,它是我的 MainActivity。但它似乎也创建了一个全新的进程,而不是仅仅打开我当前正在运行的应用程序。

我缺少一些标志吗?

【问题讨论】:

  • 是您的应用在后台,那么它应该打开同一个实例。如果它被系统以某种方式杀死,那么它将创建一个新进程
  • 您还可以在清单中将活动模式设置为single_task,这样它就可以像单身人士一样工作
  • @MurtazaKhursheedHussain 我该怎么做?抱歉,我是 Android 新手。
  • 在清单中的 <activity> 标记中。 android:launchMode=["multiple" | "singleTop" |"singleTask" | "singleInstance"]developer.android.com/guide/topics/manifest/…
  • @MurtazaKhursheedHussain 这行得通!现在我只是想知道如何从 Uri 获取参数?因为 onCreate 不会再被调用了。

标签: java android android-notifications deep-linking uri-scheme


【解决方案1】:

Activity 有 LaunchModes

android:launchMode=["multiple" | "singleTop" |"singleTask" | "singleInstance"]

阅读更多关于 LaunchMode here

这可以放在manifest 的活动标签中。

要获取意图数据,请尝试onNewIntent()

【讨论】:

    【解决方案2】:

    你可以如下设置Intent,Intent动作和类别与你在AndroidManifest.xml中指定的匹配

     Intent intent = new Intent()  
                .setAction(Intent.ACTION_VIEW)  
                .addCategory(Intent.CATEGORY_DEFAULT)  
                .addCategory(Intent.CATEGORY_BROWSABLE)
                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                        Intent.FLAG_ACTIVITY_SINGLE_TOP) 
                .setPackage(getPackageName())
                .setData(uri);
    

    【讨论】:

    • 这行得通!现在我只是想知道如何从 Uri 获取参数?因为 onCreate 不会再被调用了。
    • 如果这个activity实例存在,android系统调用onNewIntent(),否则调用onCreate()
    猜你喜欢
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多