Android: how to prevent multiple instances of an activity to be launched from a widget

androidandroid-activityandroid-intentwidget

Steps to reproduce the issue:

  • the user launches my app (name of the root activity: "mainActivity") => instance A of mainActivity
  • he presses the home button (mainActivity running in background)
  • he installs the widget relative to this app
  • he clicks on the widget => a new instance of mainActivity (instance B) is displayed
  • he clicks on the the back button: the user comes back to activity A (what I don't want ! The activity B should be closed (actually, the whole app should be closed))

Do you know how to avoid this issue ? (I have seen some similar questions on stackoverflow but not stricly what I wanted)

Thanks !!!!

The code:

public class MyWidgetProvider extends AppWidgetProvider {

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {

    // Build the intent to call the service//

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

    Intent openAppIntent = new Intent(context.getApplicationContext(), MainActivity.class);
    openAppIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
    PendingIntent openAppPendingIntent = PendingIntent.getActivity(context, 0, openAppIntent, 0);


    remoteViews.setOnClickPendingIntent(R.id.widgetLinearLayout, openAppPendingIntent);

//// ETC…///

    }

Best Answer

Try using:

openAppIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

description here.


You can also use:

openAppIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);

description here.