sandalone
sandalone

Reputation: 41749

Prevent notification PendingIntent starts Activity already started?

The service creates a persistent Notification and starts the main activity on click via PendingIntent. Here is the code.

Intent notificationIntent = new Intent(getApplicationContext(), ViewPagerActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(StreamingService.this, 0, notificationIntent, 0);

However, if the main activity is started when I press notification, it will be started again, and again and...

In the end, I have the same activity pilled up, one on the top of another. I can see this by pressing the back button, which will kill the Main activity once and then get me back to the same activity until I close the last one.

How can I prevent this to happen? Can PendingIntent detect that aiming activity is running so it does not create the same activity again, but rather start the running one?

PS. I apologize if not being able to explain this well. If this is the case, let me know and I will rephrase the problem.

Upvotes: 7

Views: 7018

Answers (3)

JunsungChoi
JunsungChoi

Reputation: 87

Try using another value in REQUEST_CODE. don't use default value 0 in REQUEST_CODE.

or your pendingIntent will restart your activity.

if you want to use normal activity cycle, input request value when creating PendingIntent.

PendingIntent resultPendingIntent = PendingIntent.getActivity(
        context, REQUEST_CODE,
        resultIntent,
        PendingIntent.FLAG_UPDATE_CURRENT);

Upvotes: 1

sandalone
sandalone

Reputation: 41749

I also found this solution. Add this attribute to Manifest

           <activity android:name=".MyActivity"
              android:label="@string/app_name"
              android:launchMode="singleTop"      // <-- THIS LINE
            >

for each Activity you need this feature. So far it work with no errors at all.

Which solution is better? Mine is easier, if nothing.

Upvotes: 8

etienne
etienne

Reputation: 3206

Depending on the exact behaviour you want to implement, you could pass one of these flags as the last param of getActivity():

Upvotes: 6

Related Questions