Android全局退出的两种方法

第一种方法参考《第一行代码》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。

原文地址:https://www.cnblogs.com/xurui1995/p/5759662.html