Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bring Android existing activity to front via notification

Tags:

android

I have one Android application, when it runs a service, I want to show the notification on the status bar. Then the user could navigate to other application by pressing HOME key. However when I try to bring the previous running application back to Front via notification icon, there is some problem with the existing activity. Even I declare it as "Single Top" mode (I want to run the existing activity since there is an associated service running) , somehow that activity's OnDestroy has been called before OnResume. Here is my code of creating the notification object. Could you please point me what wrong it is. Thanks.

private void showNotification ()
{

  Intent toLaunch = new Intent(getApplicationContext(),
                                          MySingleTopActivity.class);

  PendingIntent intentBack = PendingIntent.getActivity(getApplicationContext(),   0,toLaunch, PendingIntent.FLAG_UPDATE_CURRENT);

  notification.setLatestEventInfo(getApplicationContext(),
         getText(R.string.GPS_service_name), text, intentBack);
....
}
like image 838
user404012 Avatar asked Jul 28 '10 18:07

user404012


People also ask

Can Android activity run in background?

It seems like you want to run an activity in background when it quits. However, activity can't be run unless it's on foreground. In order to achieve what you want, in onPause(), you should start a service to continue the work in activity. onPause() will be called when you click the back button.

How does Android know which activity to run first?

Android does not grab whichever one appears first in the manifest but it starts with activity having CATEGORY_LAUNCHER. CATEGORY_LAUNCHER : The activity can be the initial activity of a task and is listed in the top-level application launcher. Save this answer.

How do you handle notifications when an app is in foreground in firebase?

Firebase notifications behave differently depending on the foreground/background state of the receiving app. If you want foregrounded apps to receive notification messages or data messages, you'll need to write code to handle the onMessageReceived callback.


1 Answers

private void showNotification() {
    Intent toLaunch = new Intent(getApplicationContext(), MySingleTopActivity.class);

    //add these two lines will solve your issue
    toLaunch.setAction("android.intent.action.MAIN");
    toLaunch.addCategory("android.intent.category.LAUNCHER");

    PendingIntent intentBack = PendingIntent.getActivity(getApplicationContext(), 0, toLaunch, PendingIntent.FLAG_UPDATE_CURRENT);

    notification.setLatestEventInfo(getApplicationContext(), getText(R.string.GPS_service_name), text, intentBack);
    ...
}
like image 134
santhosh Avatar answered Nov 16 '22 02:11

santhosh