Android 退出 App
- 结束当前 App 的所有 Activity。
- 结束当前 App 进程。
结束当前 App 进程
android.os.Process.killProcess(android.os.Process.myPid()); // Android 提供方法
// System.exit(0); // Java 结束进程方法,0-正常退出;1-异常退出
// System.exit(1);
public class ActivityCollector {
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();
}
}
activities.clear();
}
public static void exitApp(){
finishAll();
android.os.Process.killProcess(android.os.Process.myPid());
}
}
//BaseActivity应用
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("BaseActivity", getClass().getSimpleName());
ActivityCollector.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
}
Android 再按一次退出 App
// 再点一次退出程序时间设置
private long TOUCH_TIME = 0L;
private static final long WAIT_TIME = 2000L;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if(keyCode == KeyEvent.KEYCODE_BACK){
if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
ActivityCollector.exitApp();
} else {
TOUCH_TIME = System.currentTimeMillis();
Toast.makeText(this, "在按一次退出", Toast.LENGTH_SHORT).show();
}
return true;
}
return super.onKeyDown(keyCode, event);
}