Android中双击返回键退出应用实例代码
作者:印象丶亮仔 时间:2022-02-20 00:28:44
Android中双击返回键退出程序
1.在MyAppliction中(继承Application)
//运用list来保存们每一个activity是关键
private List<Activity> mList = new LinkedList<Activity>();
//为了实现每次使用该类时不创建新的对象而创建的静态对象
private static MyApplication instance;
//构造方法
public MyApplication() {
}
//实例化一次
public synchronized static MyApplication getInstance() {
if (null == instance) {
instance = new MyApplication();
}
return instance;
}
//添加要退出的Activity
public void addActivity(Activity activity) {
mList.add(activity);
}
//关闭每一个list内的activity
public void exit() {
try {
for (Activity activity : mList) {
if (activity != null)
activity.finish();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
//杀进程
public void onLowMemory() {
super.onLowMemory();
System.gc();
}
2.在你需要的关闭的Activity的onCreact()中加入
MyApplication.getInstance().addActivity(this);
3.你需要双击返回退出的界面加上
/**
* 两次返回退出
*/
private long mExitTime;
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if ((System.currentTimeMillis() - mExitTime) > 3000) {
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
mExitTime = System.currentTimeMillis();
} else {
MyApplication.getInstance().exit();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
来源:http://blog.csdn.net/qq_23179075/article/details/60587202
标签:android,双击,退出
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
深入分析JAVA 建造者模式
2023-03-14 01:32:27
![](https://img.aspxhome.com/file/2023/8/66708_0s.jpg)
Java基础之反射
2021-12-20 17:20:20
![](https://img.aspxhome.com/file/2023/0/82450_0s.png)
Java中byte输出write到文件的实现方法讲解
2023-12-25 11:11:36
SpringBoot利用拦截器实现避免重复请求
2022-02-07 00:21:53
![](https://img.aspxhome.com/file/2023/1/68021_0s.png)
Spring容器的创建过程之如何注册BeanPostProcessor详解
2022-02-17 08:39:09
![](https://img.aspxhome.com/file/2023/2/65172_0s.png)
Spring Boot配置接口WebMvcConfigurer的实现
2023-11-27 23:28:50
![](https://img.aspxhome.com/file/2023/3/60523_0s.png)
C#数据结构之单链表(LinkList)实例详解
2021-09-15 21:40:14
![](https://img.aspxhome.com/file/2023/3/100083_0s.png)
Java 中普通代码块,构造代码块,静态代码块区别及代码示例
2022-07-03 03:54:21
Java类和对象的设计原理
2023-10-06 07:00:32
解决springcloud中Feign导入依赖为unknow的情况
2022-02-03 14:05:45
Java 面试题和答案 -(上)
2023-10-08 08:15:56
C#基于DBContext(EF)实现通用增删改查的REST方法实例
2021-06-23 20:56:07
Android线程间通信 Handler使用详解
2022-10-16 09:22:33
Spring Cloud下OAUTH2注销的实现示例
2023-06-01 22:54:58
![](https://img.aspxhome.com/file/2023/5/90975_0s.jpg)
浅析Java中如何实现线程之间通信
2022-08-24 14:28:36
.net文件上传时实现通过文件头确认文件类型的方法
2021-08-01 09:05:32
Android监听键盘状态获取键盘高度的实现方法
2023-12-02 16:44:17
C#复杂XML反序列化为实体对象两种方式小结
2022-08-05 16:50:45
![](https://img.aspxhome.com/file/2023/4/82214_0s.png)
springboot读取文件,打成jar包后访问不到的解决
2023-07-14 13:56:35
Spring中事务传播行为的介绍
2023-06-24 01:21:01