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

Time:11-02

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?

CodePudding user response:

I am not sure is this right way but it is works.

  1. Set in manifest file for the Main activity android:launchMode="singleTop".

  2. In Main activity in ocCreate() method:

     if( !isTaskRoot() ){
         finish();
     }
    

So if system open new Main activity by tap on a widget (taskId will be the same) and put it on the top of back stack then just finish it.

CodePudding user response:

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,
        PackageManager.getLaunchIntentForPackage("my.package.name"),
        PendingIntent.FLAG_IMMUTABLE ) );

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

  • Related