Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android. Switch between 2 activities without re-creating and finishing

I have 2 activities "A" and "B". I need to switch between them without finishing and recreating.

Run app -> create and show A -> press button -> create and show B -> press button -> show already exist A -> press button -> show already exist B -> and so on.

Current solution:

private void toA() {
    Intent intentToA = new Intent(this, A.class);
    intentToA.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intentToA);
}

private void toB() {
    Intent intentToB = new Intent(this, B.class);
    intentToB.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intentToB);
}

It works on VM (native, Genymotion - android 4.1). Activities will created only once. And when I switch between them, everyting is okay - no calls of the onCreate or onDestroy. It is exactly what I want.

But when I run same app on real device (Nexus 4 - android 4.3) activities are destroyed and recreated while switching.

on VM:

Run app -> 
A: onCreate, onResume -> 
press button -> 
B: onCreate, onResume -> 
press button -> 
A: onResume - > 
press button -> 
B: onResume -> 
...

on Real Device:

Run app -> 
A: onCreate, onResume -> 
press button -> 
B: onCreate, onResume & A: onDestroy ->
press buttom ->
A: onCreate, onResume & B: onDestory ->
...

Note: Intent flag has no effect on the switch behavior.

like image 602
Binakot Avatar asked Jan 14 '16 07:01

Binakot


People also ask

How can I pass value from one activity to another activity in Android without intent?

This example demonstrate about How to send data from one activity to another in Android without intent. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do I go back to first activity on Android?

Declare A in your manifest with the android:launchMode="singleTask" . This way, when you call startActivity() from your other activies, and A is already running, it will just bring it to the front. Otherwise it'll launch a new instance.


1 Answers

Set launchMode of Activities to singleInstance in AndroidManifest.xml

Hope this helps.

like image 54
Mustansar Saeed Avatar answered Sep 19 '22 00:09

Mustansar Saeed