Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Click event for Status bar notification

I've got the following code to create a status bar notification:

public void txtNotification(int id, String msg){
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(android.R.drawable.sym_action_email, msg, System.currentTimeMillis());

    // The PendingIntent will launch activity if the user selects this notification
    Intent intent = new Intent(this, MainActivity.class)
    intent.putExtra("yourpackage.notifyId", id);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 0);

    notification.setLatestEventInfo(this, "title", msg, contentIntent);

    manager.notify(id, notification);
}

When the notification is clicked, I want to call a method, preferrably with access to the id of the notification.

Thanks in advance,

Tim

(EDIT: I updated my code after reading the first answer, but I still don't know how to listen for the intent)

like image 444
Tim van Dalen Avatar asked Dec 03 '10 11:12

Tim van Dalen


1 Answers

I think the best way for you to handle a click on the notification (maybe the only way?) is to define a method within the class your PendingIntent calls (MainActivity in this case). You can modify your intent before passing it into getActivity() to include the id of the notification:

// The PendingIntent will launch activity if the user selects this notification
Intent intent = new Intent(this, MainActivity.class)
intent.putExtra("yourpackage.notifyId", id);
PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 0);

Then watch for this intent within MainActivity and call the method you defined within the class to handle the notification. You can extract the id from the incoming Intent.

Update:

In order for your Activity to handle the notification, you'll need to first define the Activity in your AndroidManifest.xml file, including any intent filters you need. Then in your Activity's onStart() you can extract the extras from the incoming intent, and act upon that data. This is a high level overview, so I suggest you read parts of the Dev Guide to familiarize yourself with the concepts. The following page is a good place to start:

http://developer.android.com/guide/topics/fundamentals.html

Also "yourpackage" should be replaced with the name of the package that includes your Class, such as "com.project.foo".

like image 61
McStretch Avatar answered Oct 30 '22 21:10

McStretch