大家好,欢迎来到IT知识分享网。
实现android双击后退键退出当前APP功能
实现该功能基本思路是,
1, 监听后退键 , 比较两次后退间隔 , 低于两秒则出发退出
2, 退出当前APP
我选择在基类中BaseActivity 中设置监听,代码如下:
@Override 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) { } } }
View Code
思路就是在每次activity 压入activity栈中管理
在退出时遍历栈,挨个finish
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/33825.html