Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Thursday, April 28, 2016

How to send parameters from a notification-click to an activity?

How to send parameters from a notification-click to an activity?


I can find a way to send parameters to my activity from my notification.

I have a service that creates a notification. When the user clicks on the notification I want to open my main activity with some special parameters. E.g an item id, so my activity can load and present a special item detail view. More specific, I'm downloading a file, and when the file is downloaded I want the notification to have an intent that when clicked it opens my activity in a special mode. I have tried to use putExtra on my intent, but cant seem to extract it, so I think I'm doing it wrong.

Code from my service that creates the Notification:

        // construct the Notification object.       final Notification notif = new Notification(R.drawable.icon, tickerText, System.currentTimeMillis());          final RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);      contentView.setImageViewResource(R.id.image, R.drawable.icon);      contentView.setTextViewText(R.id.text, tickerText);      contentView.setProgressBar(R.id.progress,100,0, false);      notif.contentView = contentView;                Intent notificationIntent = new Intent(context, Main.class);      notificationIntent.putExtra("item_id", "1001"); // <-- HERE I PUT THE EXTRA VALUE      PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);      notif.contentIntent = contentIntent;        nm.notify(id, notif);  

Code from my Activity that tries to fetch the extra parameter from the notification:

 public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);        setContentView(R.layout.main);          Bundle extras = getIntent().getExtras();      if(extras != null){          Log.i( "dd","Extra:" + extras.getString("item_id") );      }  

The extras is always null and I never gets anything into my log.

Btw... the onCreate is only run when my activity starts, if my activity is already started I also want to collect the extras and present my activity according to the item_id I receive.

Any ideas?

Answer by Lucas S. for How to send parameters from a notification-click to an activity?


Take a look at this guide (creating a notification) and to samples ApiDemos "StatusBarNotifications" and "NotificationDisplay".

For managing if the activity is already running you have two ways:

  1. Add FLAG_ACTIVITY_SINGLE_TOP flag to the Intent when launching the activity, and then in the activity class implement onNewIntent(Intent intent) event handler, that way you can access the new intent that was called for the activity (which is not the same as just calling getIntent(), this will always return the first Intent that launched your activity.

  2. Same as number one, but instead of adding a flag to the Intent you must add "singleTop" in your activity AndroidManifest.xml.

If you use intent extras, remeber to call PendingIntent.getActivity() with the flag PendingIntent.FLAG_UPDATE_CURRENT, otherwise the same extras will be reused for every notification.

Answer by Vidar Vestnes for How to send parameters from a notification-click to an activity?


After reading some email-lists and other forums i found that the trick seems to add som unique data to the intent.

like this:

   Intent notificationIntent = new Intent(Main.this, Main.class);     notificationIntent.putExtra("sport_id", "sport"+id);     notificationIntent.putExtra("game_url", "gameURL"+id);       notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime())));  

I dont understand why this needs to be done, It got something to do with the intent cant be identified only by its extras...

Answer by pinaise for How to send parameters from a notification-click to an activity?


Maybe a bit late, but: instead of this:

public void onNewIntent(Intent intent){      Bundle extras = intent.getExtras();      Log.i( "dbg","onNewIntent");        if(extras != null){          Log.i( "dbg", "Extra6 bool: "+ extras.containsKey("net.dbg.android.fjol"));          Log.i( "dbg", "Extra6 val : "+ extras.getString("net.dbg.android.fjol"));        }      mTabsController.setActiveTab(TabsController.TAB_DOWNLOADS);  }  

Use this:

Bundle extras = getIntent().getExtras();  if(extras !=null) {      String value = extras.getString("keyName");  }  

Answer by jamchen for How to send parameters from a notification-click to an

activity?

Encounter same issue here. I resolve it by using different request code, use same id as notification, while creating PendingIntent. but still don't know why this should be done.

PendingIntent contentIntent = PendingIntent.getActivity(context, **id**, notificationIntent, 0);  notif.contentIntent = contentIntent;  nm.notify(**id**, notif);  

Answer by Muhammad Yousaf Sulahria for How to send parameters from a notification-click to an activity?


I had the similar problem my application displays message notifications. When there are multiple notifications and clicking each notification it displays that notification detail in a view message activity. I solved the problem of same extra paramters is being received in view message intent.

Here is the code which fixed this. Code for creating the notification Intent.

Intent notificationIntent = new Intent(getApplicationContext(), viewmessage.class);  notificationIntent.putExtra("NotificationMessage", notificationMessage);  notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);  PendingIntent pendingNotificationIntent = PendingIntent.getActivity(getApplicationContext(),notificationIndex,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);  notification.flags |= Notification.FLAG_AUTO_CANCEL;  notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingNotificationIntent);  

Code for view Message Activity.

@Override  protected void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);        onNewIntent(getIntent());  }    @Override  public void onNewIntent(Intent intent){      Bundle extras = intent.getExtras();      if(extras != null){          if(extras.containsKey("NotificationMessage"))          {              setContentView(R.layout.viewmain);              // extract the extra-data in the Notification              String msg = extras.getString("NotificationMessage");              txtView = (TextView) findViewById(R.id.txtMessage);              txtView.setText(msg);          }      }      }  

Answer by Dheeraj Sachan for How to send parameters from a notification-click to an activity?


I tried everything but nothing worked.

eventually came up with following solution.

1- in manifest add for the activity android:launchMode="singleTop"

2- while making pending intent do the following, use bundle instead of directly using intent.putString() or intent.putInt()

                    Intent notificationIntent = new Intent(getApplicationContext(), CourseActivity.class);                        Bundle bundle = new Bundle();                      bundle.putString(Constants.EXAM_ID,String.valueOf(lectureDownloadStatus.getExamId()));                      bundle.putInt(Constants.COURSE_ID,(int)lectureDownloadStatus.getCourseId());                      bundle.putString(Constants.IMAGE_URL,lectureDownloadStatus.getImageUrl());                        notificationIntent.putExtras(bundle);                        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |                              Intent.FLAG_ACTIVITY_SINGLE_TOP);                      PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),                              new Random().nextInt(), notificationIntent,                              PendingIntent.FLAG_UPDATE_CURRENT);   

Answer by Miguel Jesus for How to send parameters from a notification-click to an activity?


AndroidManifest.xml

Include launchMode="singleTop"

  

SMSReceiver.java

Set the flags for the Intent and PendingIntent

Intent intent = new Intent(context, MessagesDetailsActivity.class);      intent.putExtra("smsMsg", smsObject.getMsg());      intent.putExtra("smsAddress", smsObject.getAddress());      intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);        PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);  

MessageDetailsActivity.java

onResume() - gets called everytime, load the extras.

Intent intent = getIntent();      String extraAddress = intent.getStringExtra("smsAddress");      String extraBody = intent.getStringExtra("smsMsg");  

Hope it helps, it was based on other answers here on stackoverflow, but this is the most updated that worked for me.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Related Posts:

0 comments:

Post a Comment

Popular Posts

Fun Page

Powered by Blogger.