Pages

Friday, August 28, 2015

Passing data from notification click event to activity android

A lot of time spend until i made it work!

I had lots of notifications and all they should trigger different events in the activity.

The data passed through intent's putExtra methods was not reliable, because of way that intent works. Some extras did not change.

The solution i ended up with is like this:

1) In my custom receiver:
Intent intent = new Intent(null, Uri.parse("some data"), context, MainActivity.class);intent.putExtra("from_notification", true);intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Create notification here. Btw logo should be set like this, because lollipop and higher logo must be only from white color:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
    iconId = R.raw.logo_white;}
else{
    iconId = R.raw.logo;}

mBuilder.setContentIntent(contentIntent);




My MainActivity:
@Overrideprotected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    boolean fromNotification = intent.getBooleanExtra("from_notification", false);
    if (fromNotification){
        String someData = intent.getData().getSchemeSpecificPart();        //some data is the unique string for each notification
    }
}

Also you should call  the method from onCreate, for cases when activity is not yet running when you tap the notification:

onNewIntent(getIntent());

And dont forget to register the receiver in manifest file with appropriate filters.

No comments:

Post a Comment