Android 实现双击退出的功能
实现android双击后退键退出当前APP功能
实现该功能基本思路是,
1,监听后退键,比较两次后退间隔,低于两秒则出发退出
2,退出当前APP
我选择在基类中BaseActivity中设置监听,代码如下:
publicvoidonBackPressed(){ //Preferences中获取是否双击退出 booleanisDoubleClick=true; //BaseApplication.get("ifDoubleClickedBack",true); if(isDoubleClick){ longcurTime=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栈
实例代码:
publicclassAppManager{ privatestaticStack<Activity>activityStack; privatestaticAppManagerinstance; privateAppManager(){ } /** *单一实例 */ publicstaticAppManagergetAppManager(){ if(instance==null){ instance=newAppManager(); } if(activityStack==null){ activityStack=newStack<Activity>(); } returninstance; } /** *获取指定的Activity * *@authorkymjs */ publicstaticActivitygetActivity(Class<?>cls){ if(activityStack!=null) for(Activityactivity:activityStack){ if(activity.getClass().equals(cls)){ returnactivity; } } returnnull; } /** *添加Activity到堆栈 */ publicvoidaddActivity(Activityactivity){ activityStack.add(activity); } /** *获取当前Activity(堆栈中最后一个压入的) */ publicActivitycurrentActivity(){ Activityactivity=activityStack.lastElement(); returnactivity; } /** *结束当前Activity(堆栈中最后一个压入的) */ publicvoidfinishActivity(){ Activityactivity=activityStack.lastElement(); finishActivity(activity); } /** *结束指定的Activity */ publicvoidfinishActivity(Activityactivity){ if(activity!=null&&activityStack.contains(activity)){ activityStack.remove(activity); activity.finish(); } } /** *结束指定的Activity */ publicvoidremoveActivity(Activityactivity){ if(activity!=null&&activityStack.contains(activity)){ activityStack.remove(activity); } } /** *结束指定类名的Activity */ publicvoidfinishActivity(Class<?>cls){ for(Activityactivity:activityStack){ if(activity.getClass().equals(cls)){ finishActivity(activity); break; } } } /** *结束所有Activity */ publicvoidfinishAllActivity(){ for(inti=0,size=activityStack.size();i<size;i++){ if(null!=activityStack.get(i)){ finishActivity(activityStack.get(i)); } } activityStack.clear(); } /** *退出应用程序 */ publicvoidAppExit(){ try{ finishAllActivity(); //System.exit(0); }catch(Exceptione){ } } }
思路就是在每次activity压入activity栈中管理
在退出时遍历栈,挨个finish
希望本文所述对大家的Android程序设计有所帮助。