Android 中退出程序有很多种方法,如建立一个全局容器,把所有的Activity存储起来,退出时循环遍历finish所有Activity;用广播的方式退出;双击两次返回键退出应用。
建立全局容器
每次启动Activity都添加到容器内,当退出程序时可以结束所有Activity。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 添加Activity到堆栈
ActivityContainer.getInstance().addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 结束Activity从栈中移除该Activity
ActivityContainer.getInstance().removeActivity(this);
}
}
Activity 容器
class ActivityContainer {
private ActivityContainer() {
}
private static ActivityContainer instance = new ActivityContainer();
private static List<Activity> activityStack = new ArrayList<Activity>();
public static ActivityContainer getInstance() {
return instance;
}
public void addActivity(Activity activity) {
activityStack.add(activity);
}
public void removeActivity(Activity activity) {
activityStack.remove(activity);
}
/**
* 结束所有Activity
*/
public void finishAllActivity() {
for (int i = 0, size = activityStack.size(); i < size; i++) {
if (null != activityStack.get(i)) {
activityStack.get(i).finish();
}
}
activityStack.clear();
}
}
这种方法比较简单, 但是可以看到activityStack持有这Activity的强引用,也就是说当某个Activity异常退出时,activityStack没有即使释放掉引用,就会导致内存问题,
广播式
通过在BaseActivity中注册一个广播,当退出时发送一个广播,finish退出。
public class BaseActivity extends Activity {
private static final String EXITACTION = "action.exit";
private ExitReceiver exitReceiver = new ExitReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction(EXITACTION);
registerReceiver(exitReceiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(exitReceiver);
}
class ExitReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
BaseActivity.this.finish();
}
}
}
双击两次返回键退出
重写onKeyDown方法
private long exitTime = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
//两秒之内按返回键就会退出
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
以上三种是比较常用的几种退出应用程序的方式,具体还要根据项目来选择合适的退出方式。
网友评论
activity.moveTaskToBack(true);
System.exit(0);