开发过程中 需要退出APP,这个时候 就需要对退出进行处理 。我最常用的是两种方式,第一种方式是:建立一个全局容器类将activity都保存起来,退出时候遍历所有的activity
第二种方式是建立广播,当我退出的时候发送一个退出广播。
第一种方式 定义BaseActivity 如下代码:
@Override PRotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);// 添加Activity到堆栈 AtyContainer.getInstance().addActivity(this); } @Override protected void onDestroy() { super.onDestroy();// 结束Activity&从栈中移除该Activity AtyContainer.getInstance().removeActivity(this); }}class AtyContainer { private AtyContainer() { } private static AtyContainer instance = new AtyContainer(); private static List<Activity> activityStack = new ArrayList<Activity>(); public static AtyContainer getInstance() { return instance; } public void addActivity(Activity aty) { activityStack.add(aty); } public void removeActivity(Activity aty) { activityStack.remove(aty); } /** * 结束所有Activity */ public static void finishAllActivity() { for (int i = 0, size = activityStack.size(); i < size; i++) { if (null != activityStack.get(i)) { activityStack.get(i).finish(); } } Log.d("调用finfshAllactivity", "-------------------"); activityStack.clear(); }在MainActivity 里面继承BaseActivity 实现如下代码:
private boolean isExit = false;@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // Toast.makeText(this, "点击两次离开", Toast.LENGTH_SHORT).show(); ToQuitTheApp(); return false; } else { return super.onKeyDown(keyCode, event); }}//封装ToQuitTheApp方法private void ToQuitTheApp() { if (isExit) { finishAllActivity(); } else { isExit = true; Toast.makeText(MainActivity.this, "再按一次退出APP", Toast.LENGTH_SHORT).show(); mHandler.sendEmptyMessageDelayed(0, 3000);// 3秒后发送消息 }}//创建Handler对象,用来处理消息Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) {//处理消息 // TODO Auto-generated method stub super.handleMessage(msg); isExit = false; }};这个时候 即可优雅退出 。
第二种方式 定义BaseActivity 代码如下
private static final String EXITACTION = "action.exit";private ExitReceiver exitReceiver = new ExitReceiver();@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); IntentFilter filter = new IntentFilter(); filter.addAction(EXITACTION); registerReceiver(exitReceiver, filter);}@Overrideprotected void onDestroy() { super.onDestroy(); unregisterReceiver(exitReceiver);}public class ExitReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "广播方式离开", Toast.LENGTH_SHORT).show(); BaseActivity2.this.finish(); }}同样在MainActivity里面 这样处理
@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) { ExitReceiver exit=new ExitReceiver(); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); exit.onReceive(MainActivity.this,intent); return super.onKeyDown(keyCode, event);}github 地址:https://github.com/yuanchongzhang/activity_exit
新闻热点
疑难解答