I have two activities. Say Activity A
and Activity B
.
From Activity A
I click a button to launch Activity B
This is the code I use for this:
Intent intent = new Intent(this, ActivityB.class);
this.startActivity(intent);
Activity B
. On the on create method of Activity B
, I enable the up button.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_news);
getActionBar().setDisplayHomeAsUpEnabled(true); //Here//
}
and on the event handle for the "up" button, i have this code:
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case android.R.id.home:
finish();
NavUtils.navigateUpFromSameTask(this);
default:
return super.onOptionsItemSelected(item);
}
}
Activity A
I click the up button in the action bar which looks like this:
Now the problem is, when I click the "up button", it goes back to Activity A
which is fine, but it restarts it. How can make it stop restarting? I just want it to resume.
When I use my hardware back button, it works as expected. i.e it goes to Activity A
and resumes it instead of restarting it.
I want my activity to resume because on that activity, I download some string online and so I don't want it to keep re downloading the data when a users goes from Activity B -> Activity A
Activity B
section looks like this:
<activity
android:name="com.example.android.ActivityB"
android:label="@string/title_activity_view_news"
android:parentActivityName="com.example.android.ActivityA">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.android.ActivityA" />
</activity>
android:launchMode="singleTop"
so it now looks like this:
<activity
android:name="com.example.android.ActivityA"
android:label="@string/app_name"
android:launchMode="singleTop"> //**HERE**//
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Should've added as an answer instead of a comment.. but here you go so you can accept if you want so others can see if necessary.
https://stackoverflow.com/a/16147110/3286163
Basically, to summarize the android will always recreate the activity unless you specify it not to with
android:launchMode="singleTop"
Note: it will not work if the returning activity is not on the top of the back stack as mentioned in the reference.
For anyone else, please upvote the answer in the url instead of mine if you find this useful.