Jesus Dimrix
Jesus Dimrix

Reputation: 4568

How do you avoid more than one instance of an Activity when created from widget?

I would like to start my application\activity when a button is pressed in my widget.

I am using this code:

    Intent launchApp = context.getPackageManager()


        Intent launchApp = context.getPackageManager()
                .getLaunchIntentForPackage("com.sexy.code");
        launchApp.setData(Uri.parse(listItemClickIntent
                .toUri(Intent.URI_INTENT_SCHEME)));
        pIntent = PendingIntent.getActivity(context, 0, launchApp,
                PendingIntent.FLAG_UPDATE_CURRENT);

My problem is in a scenario that my application is already alive in the background so everything looks ok until I close that activity that opened and discover another one behind it. It's like I need to exit the application twice.

How do I avoid this?

Upvotes: 1

Views: 119

Answers (2)

JDJ
JDJ

Reputation: 4328

Try this:

launchApp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

From the documentation for FLAG_ACTIVITY_CLEAR_TOP:

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

This flag can also be combined with FLAG_ACTIVITY_NEW_TASK, as in:

launchApp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                   Intent.FLAG_ACTIVITY_NEW_TASK);

You can also use them separately, depending on what your desired behavior is.

Upvotes: 1

Nickolai Astashonok
Nickolai Astashonok

Reputation: 2888

What about using launch mode flag:

android:launchMode="singleTask"

You activity should look like:

 <activity
            android:name=".YourActivity"
            android:launchMode="singleTask"
            android:configChanges="orientation|screenSize" >

Upvotes: 0

Related Questions