Objective: to complete the exit and login of Android APP
Idea: store multiple open activities in the List, open an addList, close a removeList, create a public APPCompatActivity base class (complete the activities add and remove in the base class, and the registration and cancellation of the broadcast receiver). When clicking the "exit login" button, close all open activities, and finally start LoginActivity
Here is the code:
1. Activity list control class
public class ActivityCollector { private ActivityCollector() {} private static List<Activity> actList = new ArrayList<>(); public static void addActivity(Activity act) { actList.add(act); } public static void removeActivity(Activity act) { actList.remove(act); } public static void finishAll() { for (Activity act : actList) { if (!act.isFinishing()) { act.finish(); } } } }
2. Public base class of AppCompatActivity
public class BaseCompatActivity extends AppCompatActivity { protected LoginOutBroadcastReceiver locallReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // When you create an activity, add it to the manager ActivityCollector.addActivity(this); } @Override protected void onResume() { super.onResume(); // Register broadcast receiver IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.gesoft.admin.loginout"); locallReceiver = new LoginOutBroadcastReceiver(); registerReceiver(locallReceiver, intentFilter); } @Override protected void onPause() { super.onPause(); // Unregister broadcast receiver unregisterReceiver(locallReceiver); } @Override protected void onDestroy() { super.onDestroy(); // When you destroy an activity, remove it from the manager ActivityCollector.removeActivity(this); } }
3. Implementation of exit receiver
public class LoginOutBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ActivityCollector.finishAll(); // Destroy all activities Intent intent1 = new Intent(context, MainActivity.class); context.startActivity(intent1); } }
4. Exit button
/** * Logout */ private void loginOut() { Intent intent = new Intent("com.gesoft.admin.loginout"); sendBroadcast(intent); }