Android 实现双击退出的功能
实现android双击后退键退出当前APP功能
实现该功能基本思路是,
1, 监听后退键 , 比较两次后退间隔 , 低于两秒则出发退出
2, 退出当前APP
我选择在基类中BaseActivity 中设置监听,代码如下:
public void onBackPressed() { //Preferences 中获取是否双击退出 boolean isDoubleClick = true; //BaseApplication.get("ifDoubleClickedBack", true); if (isDoubleClick) { long curTime = SystemClock.uptimeMillis(); if ((curTime - mBackPressedTime) < (2 * 1000)) { finish(); //activity栈管理 AppManager.getAppManager().AppExit(); } else { mBackPressedTime = curTime; Toast.makeText(this, "再次点击退出", Toast.LENGTH_SHORT).show(); } } else { finish(); } }
在退出当前APP中,参考开源中国,封装了activity栈
实例代码:
public class AppManager { private static Stack<Activity> activityStack; private static AppManager instance; private AppManager() { } /** * 单一实例 */ public static AppManager getAppManager() { if (instance == null) { instance = new AppManager(); } if (activityStack == null) { activityStack = new Stack<Activity>(); } return instance; } /** * 获取指定的Activity * * @author kymjs */ public static Activity getActivity(Class<?> cls) { if (activityStack != null) for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { return activity; } } return null; } /** * 添加Activity到堆栈 */ public void addActivity(Activity activity) { activityStack.add(activity); } /** * 获取当前Activity(堆栈中最后一个压入的) */ public Activity currentActivity() { Activity activity = activityStack.lastElement(); return activity; } /** * 结束当前Activity(堆栈中最后一个压入的) */ public void finishActivity() { Activity activity = activityStack.lastElement(); finishActivity(activity); } /** * 结束指定的Activity */ public void finishActivity(Activity activity) { if (activity != null && activityStack.contains(activity)) { activityStack.remove(activity); activity.finish(); } } /** * 结束指定的Activity */ public void removeActivity(Activity activity) { if (activity != null && activityStack.contains(activity)) { activityStack.remove(activity); } } /** * 结束指定类名的Activity */ public void finishActivity(Class<?> cls) { for (Activity activity : activityStack) { if (activity.getClass().equals(cls)) { finishActivity(activity); break; } } } /** * 结束所有Activity */ public void finishAllActivity() { for (int i = 0, size = activityStack.size(); i < size; i++) { if (null != activityStack.get(i)) { finishActivity(activityStack.get(i)); } } activityStack.clear(); } /** * 退出应用程序 */ public void AppExit() { try { finishAllActivity(); // System.exit(0); } catch (Exception e) { } } }
思路就是在每次activity 压入activity栈中管理
在退出时遍历栈,挨个finish
希望本文所述对大家的Android程序设计有所帮助。
赞 (0)