从通知中调用onNewIntent()

jwB*_*ide 3 android android-intent

MainActivity托管我的所有片段.

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

我的印象是我可以从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());

}
Run Code Online (Sandbox Code Playgroud)

在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();

    }

}
Run Code Online (Sandbox Code Playgroud)

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

Nit*_*esh 8

尝试launchMode of your activity as "singleTop"在清单中设置.

来自官方文件.

这被称为在其包中将launchMode设置为"singleTop"的活动,或者在调用startActivity(Intent)时客户端使用FLAG_ACTIVITY_SINGLE_TOP标志.在任何一种情况下,当在活动堆栈的顶部而不是正在启动的活动的新实例重新启动活动时,将在现有实例上使用用于重新启动的Intent调用onNewIntent()它.

在接收新意图之前,活动将始终暂停,因此您可以指望在此方法之后调用onResume().

请注意,getIntent()仍然返回原始Intent.您可以使用setIntent(Intent)将其更新为此新Intent.