Android退出登入總結
阿新 • • 發佈:2018-12-19
目標:完成Android版APP應用的退出登入
思路:將多個開啟的Acitivity存放在List中,開啟一個addList,關閉一個removeList,建立公用APPCompatActivity基類(在基類中完成活動add和remove,以及廣播接收器的註冊和取消),在點選“退出登入”按鈕時,關閉所有開啟的Activity,最後再啟動LoginActivity.
下面是程式碼:
1,活動列表控制類
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,AppCompatActivity的公共基類
public class BaseCompatActivity extends AppCompatActivity { protected LoginOutBroadcastReceiver locallReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 建立活動時,將其加入管理器中 ActivityCollector.addActivity(this); } @Override protected void onResume() { super.onResume(); // 註冊廣播接收器 IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.gesoft.admin.loginout"); locallReceiver = new LoginOutBroadcastReceiver(); registerReceiver(locallReceiver, intentFilter); } @Override protected void onPause() { super.onPause(); // 取消註冊廣播接收器 unregisterReceiver(locallReceiver); } @Override protected void onDestroy() { super.onDestroy(); // 銷燬活動時,將其從管理器中移除 ActivityCollector.removeActivity(this); } }
3,退出接收器的實現
public class LoginOutBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ActivityCollector.finishAll(); // 銷燬所有活動 Intent intent1 = new Intent(context, MainActivity.class); context.startActivity(intent1); } }
4,退出按鈕
/**
* 退出登入
*/
private void loginOut() {
Intent intent = new Intent("com.gesoft.admin.loginout");
sendBroadcast(intent);
}