0

MainActivity in my app has launchMode set to singleTask. If I start ActivityB from MainActivity, then put app to background and start my app from applications screen it does not resume correctly. ActivityB automatically finishes and MainActivity resumes. I expect ActivityB to resume instead. Why is this happening and what could I do to make it work normally? It works OK without singleTask flag but I need that flag for other purposes.

By the way, my app resumes correctly from recent apps screen.

Egis
  • 5,081
  • 5
  • 39
  • 61

2 Answers2

0

Use the following code in the LAUNCHER Activities.

@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

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

// Rest of your onCreate code goes here
}
Dmarp
  • 208
  • 1
  • 3
  • 13
0

Activity B is closed because it launched from Activity A, this is normal behavior for android because Activity A needs to be restarted (singleTask) and all related instance will be kill/finish.

So, what you can do is implement shared-preference.

your activity A should be like this :

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //// read share preference
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    int defaultValue = getResources().getInteger("MYSHARE_PRFERENCE");
    int isOpened = sharedPref.getInt("IS_ACTIVITY_B_ALREADY_OPENED", defaultValue);

    if (isOpened == 1)
    {
        //resume activity B
        startActivity(new Intent(MainActivity.this, ActivityB.class));
    }       
    ////

    findViewById(R.id.text).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this, ActivityB.class));

            //// write on share preference
            SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt("IS_ACTIVITY_B_ALREADY_OPENED", 1);
            editor.commit();
            ////
        }
    });
}

}

P.S : I didn't compile it yet, the code might be error on compile. But share preference can be solution for your problem.

AFin
  • 61
  • 2
  • Thanks for your effort to help, but starting ActivityB from MainActivity does not resume it. Activity state is lost. Apparently this problem doesn't have a solution. This question has already been asked here http://stackoverflow.com/questions/2417468/android-bug-in-launchmode-singletask-activity-stack-not-preserved – Egis Aug 22 '16 at 14:33