stealthjong stealthjong - 2 days ago 6
Android Question

Android Call method on Notification click

this code creates a notification. If you click it, the current application is ran (the intent is created in

Entry
, which is my only
Activity
), a slightly modified version of a Android Developers blog:

private void makeIntent() {
NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification note = new Notification(R.drawable.prev, "Status message!", System.currentTimeMillis());
Intent intent = new Intent(this, Entry.class);
PendingIntent pi = PendingIntent.getActivity(this, 0,intent, 0);
note.setLatestEventInfo(this, "New Email", "Unread Conversation", pi);
note.flags |= Notification.FLAG_AUTO_CANCEL;
mgr.notify(NOTIFY_ME_ID, note);
}


But I don't want to start any activity, but merely to run a method in the current activity. From what I've read so far, I guess I have to use methods like
startActivityForResult()
, use
intent-filters
and implement
onActivityResult()
, but after messing around with all those things, changing things in the
Intent
and
PendingIntent
, I still have no usable result. Is it possible to somehow just call a method in
Entry
(my Main Activity, in which the
Intent
is created), or catch any outgoing or incoming
Intents
when I click my newly made
Notification
?

PS. my apologies if this is a duplicate thread, SO is quite slow right now, I can't search properly.

Answer

Add android:launchMode="singleTop" in your activity in your manifest file, have the method protected void onNewIntent(Intent intent) { ... } and use this code:

private static final int MY_NOTIFICATION_ID = 1;
private NotificationManager notificationManager;
private Notification myNotification;

void notification() {   
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    myNotification = new Notification(R.drawable.next, "Notification!", System.currentTimeMillis());
    Context context = getApplicationContext();
    String notificationTitle = "Exercise of Notification!";
    String notificationText = "http://android-er.blogspot.com/";
    Intent myIntent = new Intent(this, YourActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(YourActivity.this, 0, myIntent, Intent.FILL_IN_ACTION);
    myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
    myNotification.setLatestEventInfo(context, notificationTitle, notificationText, pendingIntent);
    notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
Comments