Search code examples
androidandroid-activityandroid-appwidget

Open existing activity with back stack by tap on app widget. How?


I want to open my app by tap on a app widget. So.

remote_views.setOnClickPendingIntent( R.id.layout, PendingIntent.getActivity( context, 0, new Intent( context, Main.class ).setFlags( Intent.FLAG_ACTIVITY_NEW_TASK ), PendingIntent.FLAG_IMMUTABLE ) );

But I want to open existing app and keep back stack. If I remove Intent.FLAG_ACTIVITY_NEW_TASK then on new Android I get:

java.lang.RuntimeException: Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.

I can set in manifest file

    <activity
        android:name=".Main"
        android:launchMode="singleInstance"
        android:exported="true"
        >

and open existing activity but lost back stack in addition then press Home button and launch the app again by icon then back stack lost too.

So, is it possible?


Solution

  • Use a launch Intent. This will just bring the existing task to the foreground in whatever state it was in. If it isn't already running, it will start it the same way it would start if the user tapped on the app icon in the HOME screen:

    remote_views.setOnClickPendingIntent( R.id.layout,
        PendingIntent.getActivity(
            context, 0,
            context.getPackageManager().getLaunchIntentForPackage("my.package.name"),
            PendingIntent.FLAG_IMMUTABLE ) );
    

    You do not need any special launch mode in the manifest for your MainActivity.