android - 从通知调用 onNewIntent()

标签 android android-intent

MainActivity 托管我所有的 fragment 。

当用户点击从 Google Cloud Messaging 收到的通知时,我需要显示一个特定 fragment 。

我的印象是我可以从 onNewIntent() 处理这个问题,但是在我按下通知后这个方法似乎没有触发。

这是我的 GcmIntentService 类中的发送通知方法:

private void sendNotification(String message, String eventId) {

    mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.putExtra(Constants.eventIdBundleKey, eventId);

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
            Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_test)
                    .setContentTitle(getString(R.string.app_name))
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(message))
                    .setContentText(message);
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

}

在 MainActivity 中,我正在尝试接收和处理:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);


    if(intent.hasExtra(Constants.eventIdBundleKey)) {

        Fragment fragment = GiftsPriceFragment.newInstance(Common.retrieveAppUser(this), null, null);
        mFm.beginTransaction().replace(R.id.content_frame, fragment)
                .addToBackStack(GiftsPriceFragment.FRAGMENT_TAG).commit();

    }

}

知道为什么没有调用 onNewIntent() 吗?

最佳答案

尝试在 list 中将您的 Activity 的 launchMode 设置为“singleTop”

来自官方文档。

如果 Activity 在其包中将 launchMode 设置为“singleTop”,或者如果客户端在调用 startActivity(Intent) 时使用了 FLAG_ACTIVITY_SINGLE_TOP 标志,则会调用此方法。在任何一种情况下,当 Activity 在 Activity 堆栈的顶部而不是正在启动的 Activity 的新实例重新启动时,将在现有实例上调用 onNewIntent() 并使用用于重新启动的 Intent

在接收到新的 Intent 之前, Activity 将始终暂停,因此您可以指望在此方法之后调用 onResume()。

请注意,getIntent() 仍会返回原始 Intent。您可以使用 setIntent(Intent) 将其更新为这个新的 Intent。

关于android - 从通知调用 onNewIntent(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27430985/

相关文章:

android - 如何在另一个 Activity 中重用下载的图像?

android - PendingIntent 不会启动所需的 fragment

Android - 停止广播接收器被服务杀死

android - 在自定义相机应用程序-Android 中崩溃

Android 创建一个 float 在锁屏上的 Activity

android - webview 每次显示最后一个 loadurl() 方法的内容

android - 创建 .a 文件而不是 .so 使用 android studio?

android - 什么是 Fabric API key ?

android - 随着最近的应用程序切换,从通知开始/恢复任务返回堆栈

java - 清除 Android 3.x 上的图案锁定