简体   繁体   中英

Extra null for Android Notification with PendingIntent

I am trying to send a int Extra to an Activity when a notification is tapped. When I tap the notification the activity launches, but the extra is always null.

I have checked a lot of similar questions but they haven't helped me solve the problem. (I tried using onNewIntent() but it was never called). How can I successfully send the Extra?

This is the BroadcastReceiver where the intent is created:

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);
    }
}

This is the method from NotificationsDeliver where the notification is sent:

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

This is onCreate method from EventActivity:

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

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

I would guess that it's because you have capitalized the word "id" differently when putting vs getting the extra; compare:

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

vs

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

Try using the same capitalization for both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM