【问题标题】:Extra null for Android Notification with PendingIntent带有 PendingIntent 的 Android 通知的额外 null
【发布时间】:2023-03-27 23:06:01
【问题描述】:

我正在尝试在点击通知时向 Activity 发送一个 int Extra。当我点击通知时,活动启动,但额外的始终为空。

我检查了很多类似的问题,但它们并没有帮助我解决问题。 (我尝试使用 onNewIntent() 但它从未被调用)。如何成功发送 Extra?

这是创建意图的 BroadcastReceiver:

public class EventAlarmNearReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        Intent nextIntent = new Intent().setClass(context, EventActivity.class);
        nextIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        int id = 1234;
        nextIntent.putExtra("Id", (long) id);
        nextIntent.setAction("nearReceiverAction");
        PendingIntent nextPendingIntent = PendingIntent.getActivity(context, 1022, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        String text = "Your " + intent.getStringExtra("Name") + " is starting soon. Please read your documents.";

        NotificationsDeliver.getInstance().sendNotification(context, "Meeting Mate", text, nextPendingIntent);
    }
}

这是发送通知的 NotificationsDeliver 方法:

public void sendNotification(@NonNull Context context, String title, String text, PendingIntent pendingIntent ) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_event_note_white_24dp)
                .setContentTitle(title)
                .setContentText(text)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setVibrate(new long[] { 1000, 1000, 1000 })
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        // notificationId is a unique int for each notification that you must define
        notificationManager.notify(999, builder.build());
    }

这是来自 EventActivity 的 onCreate 方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();
    long id = intent.getLongExtra("id", 0);
}

【问题讨论】:

    标签: java android android-intent android-notifications android-pendingintent


    【解决方案1】:

    我猜这是因为你在 put 和 getting the extra 时把“id”这个词大写的不同;比较:

    nextIntent.putExtra("Id", (long) id);
    //                  ^^^^
    

    long id = intent.getLongExtra("id", 0);
    //                            ^^^^
    

    尝试对两者使用相同的大小写。

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多