標籤:
第一種方法參考《第一行代碼》78頁
建立一個ActivityCollector類,提供靜態方法addActivity,fininshAll(以list為容器)
然後我們建立的Activity都繼承一個BaseActivity,在BaseActivity中的oncreate方法中,使用ActivityCollector的addActivity(this),
想要隨時全域退出只要調用ActivityCollector.finishAll()
今天在看到另一個和Activity啟動模式有關的全域退出方法
我們寫了三個Activity,然後設定textView的點擊事件,跳轉下一個Activity,這時候我們想在第二個或第三個Activity直接退出,該怎麼做
第一步:設定MainActivity的 android:launchMode="singleTask"
singleTask
- 判斷Activity所需任務棧內是否已經存在,如果存在,就把該Activity切換到棧頂(會導致在它之上的都會出棧)
- 如果所需任務棧都不存在,就會先建立任務棧再建立該Activity
- 可以理解為 頂置Activity+singleTop 的模式
第二步:我們建立一個BackUtils類
import android.app.Activity;import android.content.Intent;public class BackUtils { public static void allBack(Activity activity){ Intent intent=new Intent(activity, MainActivity.class); activity.startActivity(intent); }}
類中的AllBack方法就是去啟動MainActivity。
我們可以在其他Activity中複寫
@Override
public void onBackPressed() {
super.onBackPressed();
BackUtils.allBack(this);
}
這時候,可以思考到,MainActivity是singletask,這樣來到MainActivy,棧中MainActivy上面的都會出棧,但是這時候還剩下一個MainActivity,
我們做的就是要來到MainActivity後立即銷毀它。
這時,剛好存在方法
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
finish();
}
對於這個方法
This is called for activities that set launchMode to "singleTop" in their package, or if a client used the Intent.FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity. In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.
An activity will always be paused before receiving a new intent, so you can count on onResume being called after this method.
這裡的onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.我們的MainActivity使我們進去App的第一個介面,所以必然已經存在,當設定singleTop或者singleTask時,會調用onNewIntent()。
我們只要在onNewIntent()調用finish。
Android全域退出的兩種方法