做項(xiàng)目的時(shí)候,涉及到一個(gè)注銷登錄的過程,這時(shí)候需要關(guān)閉之前打開的所有Activity。僅finish當(dāng)前Activity顯然是不夠的,需要把返回棧中的Activity一個(gè)個(gè)銷毀。我實(shí)踐過的方法有兩種:
創(chuàng)新互聯(lián)企業(yè)建站,10年網(wǎng)站建設(shè)經(jīng)驗(yàn),專注于網(wǎng)站建設(shè)技術(shù),精于網(wǎng)頁設(shè)計(jì),有多年建站和網(wǎng)站代運(yùn)營經(jīng)驗(yàn),設(shè)計(jì)師為客戶打造網(wǎng)絡(luò)企業(yè)風(fēng)格,提供周到的建站售前咨詢和貼心的售后服務(wù)。對(duì)于成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)中不同領(lǐng)域進(jìn)行深入了解和探索,創(chuàng)新互聯(lián)在網(wǎng)站建設(shè)中充分了解客戶行業(yè)的需求,以靈動(dòng)的思維在網(wǎng)頁中充分展現(xiàn),通過對(duì)客戶行業(yè)精準(zhǔn)市場調(diào)研,為客戶提供的解決方案。1、基礎(chǔ)類BaseActivity中注冊(cè)廣播接收器,接受關(guān)閉所有Activity的廣播
2、基礎(chǔ)類BaseActivity中將Activity加入一個(gè)集合中,并提供一個(gè)靜態(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中注冊(cè)銷毀廣播接收器:
public class BaseActivity extendsAppCompatActivity { private static final String TAG = "BaseActivity"; private ExitAppReceiver exitAppReceiver; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerExitAppReceiver();//注冊(cè) } @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 Listlist = 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); }
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國云服務(wù)器,動(dòng)態(tài)BGP最優(yōu)骨干路由自動(dòng)選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動(dòng)現(xiàn)已開啟,新人活動(dòng)云服務(wù)器買多久送多久。