意图额外信息未被接收

3

我正在展示一个与我的项目相关的库中的通知,当点击通知时,通知会跳转到一个Activity(ReceivingActivity)。点击通知后,Activity会打开,但是附加在其中的extras没有被接收到。

通知触发代码 - 当我收到gcm消息时,我调用sendNotification,而通知代码位于库中。

public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
private void sendNotification(Bundle extras) {
    mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);



    Intent redirectIntent = new Intent(this, Class.forName("com.xyz.kljdf.ReceivingActivity"));
            redirectIntent.putExtra("key", "value"); // These extras are not received in ReceivingActivity onCreate(), see the code below




    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            redirectIntent, 0);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
    .setSmallIcon(((Context)this).getResources().getIdentifier("icon", "drawable", getPackageName()))
    .setContentTitle(extras.getString(PushConstants.TITLE))
    .setStyle(new NotificationCompat.BigTextStyle()
    .bigText(extras.getString(PushConstants.ALERT)))
    .setContentText(extras.getString(PushConstants.ALERT));

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

检查ReceivingActivity中的额外内容...

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_receiving);


        Log.i("extras..... @@@@@@", getIntent().getExtras().toString()); //NPE here


    }

我需要帮助弄清如何传递额外参数并正确接收它们。


https://dev59.com/wnA75IYBdhLWcg3wrbC_ - CommonsWare
1个回答

6
请确保当PendingIntent被调用时,实际上传递了数据。请参见此答案以获取解释:https://dev59.com/hHE85IYBdhLWcg3wNw14#3851414 对于其他人,如果您确定意图已经存在并且只是被带到前台,则默认情况下不会将新意图的数据传递给它。您可以重写onNewIntent(Intent)以绕过此问题。
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent); // Set the new Intent's data to be the currently passed arguments
}

活动/意图在我发送通知之前从未打开过,因此我认为这不是正确的答案。 - Yashwanth Kumar
抱歉,那么。这通常是一个常见的问题。你检查过这个了吗?https://dev59.com/hHE85IYBdhLWcg3wNw14#3851414 - Cruceo
谢谢,您发布的链接有正确的答案,请将您的回答修改为仅包含该链接,以便我接受它。 - Yashwanth Kumar
修改后,首先显示正确答案,但保留了onNewIntent(),因为在通知和PendingIntent中经常被忽视。 - Cruceo
但是如果应用程序不在堆栈中,而通知活动位于堆栈顶部,则不会调用此方法。 请帮忙。 - Saad Bilal
这就是它应该工作的方式。这是两个不同的用例。只需在setIntent(intent);行后添加一些代码,以根据传递的新意图重新设置您的Activity。还要注意,如果您不使用FLAG_ACTIVITY_NEW_TASK,则可能无法触发事件。 - Cruceo

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