如果你也遇到了需要按几下back才能退出程序的话~
可以试试这样
我们用stdio新建一个java class叫做ActivityCollector
public class ActivityCollector {
#用一个List来暂存活动
public static List<Activity> activities = new ArrayList<>();
public static void addActivity(Activity activity){
activities.add(activity);
}
public static void removeActivity(Activity activity){
activities.remove(activity);
}
public static void finishAll(){
for (Activity activity:activities){
if (!activity.isFinishing()){
activity.finish();
}
}
}
}
在新建一个BasicActivity
public class BasicActivity extends AppCompatActivity {
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
#打印当前活动
Log.d("BasicActivity",getClass().getSimpleName());
ActivityCollector.addActivity(this);
}
}
我们让所有的活动继承于BasicActivity这个父类
之后如果我们想在某个活动中点击按钮退出程序
public void onClick(View v) {
ActivityCollector.finishAll();
}
如果还想直接杀掉当前进程,可以添加如下代码:
android.os.Process.killProcess(android.os.Process.myPid());