实现android双击后退键退出当前APP功能 实现该功能基本思路是, 1, 监听后退键 , 比较两次后退间隔 , 低于两秒则出发退出 2, 退出当前APP 我选择在基类中Ba
实现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;
}
public static Activity getActivity(Class<?> cls) {
if (activityStack != null)
for (Activity activity : activityStack) {
if (activity.getClass().equals(cls)) {
return activity;
}
}
return null;
}
public void addActivity(Activity activity) {
activityStack.add(activity);
}
public Activity currentActivity() {
Activity activity = activityStack.lastElement();
return activity;
}
public void finishActivity() {
Activity activity = activityStack.lastElement();
finishActivity(activity);
}
public void finishActivity(Activity activity) {
if (activity != null && activityStack.contains(activity)) {
activityStack.remove(activity);
activity.finish();
}
}
public void removeActivity(Activity activity) {
if (activity != null && activityStack.contains(activity)) {
activityStack.remove(activity);
}
}
public void finishActivity(Class<?> cls) {
for (Activity activity : activityStack) {
if (activity.getClass().equals(cls)) {
finishActivity(activity);
break;
}
}
}
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程序设计有所帮助。
您可能感兴趣的文章:Android双击返回键退出程序的实现方法Android App中实现可以双击放大和缩小图片功能的实例Android双击退出的实现方法Android 自定义View实现单击和双击事件的方法Android中双击返回键退出应用实例代码Android 双击返回键退出程序的方法总结Android实现双击TitleBar回顶部的功能示例代码
--结束END--
本文标题: Android 实现双击退出的功能
本文链接: https://lsjlt.com/news/24509.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0