When you do a project, it involves a process of logging off, and you need to close all activity that was previously opened. Only the current activity of finish is obviously not enough. There are two methods that I have practiced:
1. Register the broadcast receiver in the base class Baseactivity and accept the broadcast of closing all activity
2, the basic class baseactivity activity into a set, and provides a static Finishall method of unified shutdown
public class Exitappreceiver extends Broadcastreceiver {
@Override
public void OnReceive (context context, Intent Intent) {
String action = Intent.getaction ();
if (Action.equals ("Exit_app")) {
if (context! = null) {
LOG.I ("Exit_app", "Onreceive:class =" +context.getclass (). GetName ());
If (context instanceof Activity) {
(Activity) (context). Finish ();
}
If (context instanceof Service) {
((Service) context). Stopself ();
}
}
}
}
}
public class Baseactivity extends Appcompatactivity {
private static final String TAG = "baseactivity";
Private Exitappreceiver Exitappreceiver;
@Override
protected void OnCreate (@Nullable Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Registerexitappreceiver ();//Register
}
@Override
protected void OnDestroy () {
Super.ondestroy ();
Unregisterexitappreceiver ();//Destroy
}
private void Registerexitappreceiver () {
Intentfilter filter = new Intentfilter ();
Filter.addaction ("Exit_app");
Exitappreceiver = new Exitappreceiver ();
Registerreceiver (exitappreceiver, filter);
}
private void Unregisterexitappreceiver () {
Unregisterreceiver (Exitappreceiver);
}
}
Send off all activity broadcasts:
Intent Intent = new Intent ("Exit_app");
Sendbroadcast (Intent);
2, using Activitycollector (method reference Guo Lin "first line of code")
Activitycollector Source
public class Activitycollector {
public static list<activity> List = new arraylist<> ();
public static void addactivity (activity activity) {
List.add (activity);
}
public static void removeactivity (activity activity) {
List.remove (activity);
}
public static void Finishallactivity () {
for (Activity activity:list) {
if (!activity.isfinishing ()) {
Activity.finish ();
}
}
}
}
To add and remove from baseactivity:
@Override
protected void OnCreate (@Nullable Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Activitycollector.addactivity (this);
}
@Override
protected void OnDestroy () {
Super.ondestroy ();
Activitycollector.removeactivity (this);
}
This article is from a "sword Siege" blog, please make sure to keep this source http://weijiancheng.blog.51cto.com/10190955/1897763
Two ways to completely close the app