Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notification opens activity, back button pressed, main activity is opened?

The best way I can describe my problem is like this:

  1. A notification is created at boot (with a BroadcastReceiver).
  2. My app main activity is opened and the home button is pressed (the app is still running in the background until the system closes it).
  3. I pull down the status bar and press on the notification previously created at boot.
  4. Some activity, different from the main one, is started.
  5. I press the back button and the main activity is displayed.

How can I prevent that last step? What I want with the back button is to go back where I was, which is the home screen (the desktop with all the widgets and app icons). My app's main activity was supposed to be running on the background, why was it called with the back button?

In case it's relevant, my code to create a notification goes like this:

public void createNotification(int notifyId, int iconId, String contentTitle, String contentText) {
    Intent intent = new Intent(mContext, NewNoteActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(AgendaNotesAdapter.KEY_ROW_ID, (long)notifyId);

    PendingIntent contentIntent = PendingIntent.getActivity(mContext, notifyId, intent, 0);

    Notification notification = new Notification(iconId, contentTitle, 0);
    notification.setLatestEventInfo(mContext, contentTitle, contentText, contentIntent);

    mNotificationManager.notify(notifyId, notification);

I tried to add a couple of more flags combinations to intent but neither of them solved my problem... Suggestions?

like image 372
rfgamaral Avatar asked Sep 30 '11 18:09

rfgamaral


1 Answers

I use this solution in my apps. Override onBackPressed (in your activity routed from notification) and check if your app is in stack or not. if not then start your root activity. User can always navigate from your root activity. This is what I do in my apps

@Override
public void onBackPressed() {
    if (isTaskRoot()) {
        Intent intent = new Intent(this,YourMainActivity.class);
        startActivity(intent);
        super.onBackPressed();
    }else {
        super.onBackPressed();
    }
}
like image 58
Mudassar Avatar answered Dec 27 '22 19:12

Mudassar