I would also recommend Fragment
on this requirement , but since your application is already implemented, you can go with this approach.
all the activities that exists before it in the stack should be finished.
Android
doesn't provide any flag to clear all the below Activities
like clearing top Activities
using clearTop
. It would be simple if we had clearBottom
:)
Ok. If your targeting Android API version from 16
, this approach will help in an optimized way. For the other lower version you need to finish each Activity
individually.
Create a BaseActivity
which will add all the Activity
Instance into a HashMap
(similar to adding Fragments to back Stack
). But here this is to just remember the Activities
in stack. You can also check the Activities
in stack using ActivityManager.RunningTaskInfo
but I don't want to make it more complex.
Declare a static variable. I prefer to do in my Application class
.
public class MyApp extends Application {
public static HashMap<String , CommonActivity > mBackStackActivities
= new HashMap<String, CommonActivity>();
}
Now, when an Activity created
add its instance to the HashMap
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApp.mBackStackActivities.put(getComponentName().getClassName(), this);
}
And,remove it when the Activity destroy
@Override
protected void onDestroy(){
MyApp.mBackStackActivities.remove(getComponentName().getClassName());
super.onDestroy();
}
Now, Override
the startActivity
method in base Activity class
and when an Activity
is startedcheck if the
Activityexists in
HashMap. If exists
finishall the below
Activityusing
finishAffinity`.
@Override
public void startActivity(Intent intent) {
if(MyApp.mBackStackActivities
.containsKey(intent.getComponent().getClassName())){
if(android.os.Build.VERSION.SDK_INT >= 16) {
Activity activity = MyApp.mBackStackActivities.get(intent.getComponent().getClassName());
// finish the activity as well as all the below Activities.
activity.finishAffinity(); // supported from API 16
}else {
// loop through all the below activity and finish it
}
}
super.startActivity(intent);
}
Finally, If you need to set android:taskAffinity
in manifest for the required Activities
, by default all the Activities
will have same Affinity name (the package name). You can leave this if you want all your Activities
to be covered.
<activity
android:name="com.example.app.activities.MainActivity"
android:label="@string/title_activity_common"
android:taskAffinity="@string/task_affinity_name">
</activity>
In string xml
<string name="task_affinity_name">com.example.app.affinity</string>
Note : As said above for lower version , you need to finish each Activity
Individually`
Find the complete source here https://gist.github.com/androidbensin/7d9261fd148c15575dd1