您好,登錄后才能下訂單哦!
做項目的時候,涉及到一個注銷登錄的過程,這時候需要關(guān)閉之前打開的所有Activity。僅finish當(dāng)前Activity顯然是不夠的,需要把返回棧中的Activity一個個銷毀。我實踐過的方法有兩種:
1、基礎(chǔ)類BaseActivity中注冊廣播接收器,接受關(guān)閉所有Activity的廣播
2、基礎(chǔ)類BaseActivity中將Activity加入一個集合中,并提供一個靜態(tài)finishAll的方法統(tǒng)一關(guān)閉
備注:App中所有Activity直接或間接繼承自BaseActivity。
一、使用廣播接收器發(fā)送統(tǒng)一銷毀廣播
ExitAppReceiver 廣播接收器代碼:
public class ExitAppReceiver extendsBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("exit_app")){ if (context != null){ if (context instanceofActivity){ ((Activity)context).finish(); } if (context instanceofService){ ((Service)context).stopSelf(); } } } } }
BaseActivity中注冊銷毀廣播接收器:
public class BaseActivity extendsAppCompatActivity { private static final String TAG = "BaseActivity"; private ExitAppReceiver exitAppReceiver; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerExitAppReceiver();//注冊 } @Override protected void onDestroy() { super.onDestroy(); unRegisterExitAppReceiver();//銷毀 } private void registerExitAppReceiver(){ IntentFilter filter = new IntentFilter(); filter.addAction("exit_app"); exitAppReceiver = new ExitAppReceiver(); registerReceiver(exitAppReceiver, filter); } private void unRegisterExitAppReceiver(){ unregisterReceiver(exitAppReceiver); } }
發(fā)送關(guān)閉所有Activity廣播:
Intent intent = new Intent("exit_app");
sendBroadcast(intent);
二、采用ActivityCollector(方法參考郭霖《第一行代碼》第2版)
ActivityCollector源碼
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(); } } } }
在BaseActivity中添加和移除:
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityCollector.addActivity(this); } @Override protected void onDestroy() { super.onDestroy(); ActivityCollector.removeActivity(this); }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。