Android: Transferring Data via ContentIntent

2019-07-15 10:58发布

问题:

I've got a problem with my Android Application. It receives Messages via Google Cloud Messaging and displays a Notification in the Notificationbar. I want to transfer some Data with the Notification. This Data comes via Google Cloud Messaging and should be attached to the Notification.

This is my Code to Display the Notification:

private void setNotification(String strTitle, String strMessage, int intPageId, int intCategorieId)
    {
        notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent intentOpen = new Intent(this, NotificationClick.class);
        intentOpen.putExtra("pageId", Integer.toString(intPageId));
        intentOpen.putExtra("categorieId", Integer.toString(intCategorieId));
        intentOpen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

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


        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.launcher_icon)
                .setTicker(strTitle)
                .setContentTitle(strTitle)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(strMessage))
                .setContentText(strMessage);


        notificationBuilder.setContentIntent(contentIntent);
        notificationBuilder.setDefaults(Notification.DEFAULT_ALL);
        notificationManager.notify(intCategorieId, notificationBuilder.build());

    }

And my Code to get the Variables "intPageId" and "intCategorieId" in a other Activity(witch opens by clicking the Notification) back, is this:

 Bundle intentExtras = new Bundle();
        intentExtras = getIntent().getExtras();
        Toast.makeText(this, "Page To Open: " + intentExtras.getString("pageId"), Toast.LENGTH_LONG).show();
        Toast.makeText(this, "Page To Open: " + intentExtras.getString("kategorieId"), Toast.LENGTH_LONG).show();

But in both "Toast" Messages appears "null", or the value that was passed through at the first time, clicking on the Message.

For Example: At the First time I send: intPageId=1. The Toast says: "Page To Open: 1".

At the Second time I send: intPageId=2. The Toast says: "Page To Open: 1".

I'm totally confused.

回答1:

First Method :

Instead of below line :

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

change it to this :

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intentOpen, PendingIntent.FLAG_UPDATE_CURRENT);

Second Method :

int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);

PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),iUniqueId, intentForNotification, 0);