0

I searched around but couldn't find an answer. My app is based on fragments, and MainActivity is the entry point. When the user clicks on a notification, I trigger the desired behaviour with a PendingIntent that contains specific flags as to what fragment needs to be invoked.

My problem occurs when the fragment I need is already being displayed. When the MainActivity is entered through the PendingIntent, the fragmentManager.getBackStackEntryCount() will return zero. I guess that this happens because the activity is a different instance than what I already had running. Then the same fragment is invoked again and this messes up my UI (and potentially crash because the Otto bus had already been registered).

My question is: what is the best way to detect the state of the running app (i.e. which fragment is being displayed) when the activity is triggered from a notification? Thanks.

ticofab
  • 7,551
  • 13
  • 49
  • 90

2 Answers2

1

I guess you could do that with the FragmentManager class. You have several interesting methods. For example, findFragmentByTag(String tag) enables you to know if a Fragment with a particular TAG exists.

Also, are you sure you are not recreating a new Activity (on top of the current one ) ?

Gordak
  • 2,060
  • 22
  • 32
0

Thanks to @Gordak suggestion, I was able to figure out my problem. What I needed was a combination of flags in my (pending)Intent:

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP);

This way, if the invoked activity is on top, it won't be destroyed (thus keeping the FragmentManager's backstack) but the method onNewIntent(Intent intent) will be triggered, letting you react to it. This is described in the documentation for FLAG_ACTIVITY_CLEAR_TOP.

ticofab
  • 7,551
  • 13
  • 49
  • 90