android 中退出程序的两种方式

转自:http://blog.sina.com.cn/s/blog_5da93c8f0100t76l.html

思考:如何安全的退出程序?

 
finish是Activity的类,仅仅针对Activity,当调用finish()时,只是将活动推向后台,并没有立即释放内存,活动的资源并没有被清理;当调用System.exit(0)时,杀死了整个进程,这时候活动所占的资源也会被释放。
在开发android应用时,常常通过按返回键(即keyCode == KeyEvent.KEYCODE_BACK)就能关闭程序,其实大多情况下该应用还在任务里运行着,其实这不是我们想要的结果。
我们可以这样做,当用户点击自定义的退出按钮或返回键时(需要捕获动作),我们在onDestroy()里强制退出应用,或直接杀死进程,具体操作代码如下:
 
 
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//按下键盘上返回按钮
if(keyCode == KeyEvent.KEYCODE_BACK){
 
new AlertDialog.Builder(this)
.setIcon(R.drawable.services)
.setTitle(R.string.prompt)
.setMessage(R.string.quit_desc)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
}).show();
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
 
 
@Override
protected void onDestroy() {
super.onDestroy();
System.exit(0);
//或者下面这种方式
//android.os.Process.killProcess(android.os.Process.myPid()); 
}
 
 
posted @   鸭子船长  阅读(339)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示