stealthjong stealthjong - 9 months ago 63
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

, which is my only
), 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
, use
and implement
, but after messing around with all those things, changing things in the
, I still have no usable result. Is it possible to somehow just call a method in
(my Main Activity, in which the
is created), or catch any outgoing or incoming
when I click my newly made

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

Answer Source

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(, "Notification!", System.currentTimeMillis());
    Context context = getApplicationContext();
    String notificationTitle = "Exercise of Notification!";
    String notificationText = "";
    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);