标签:
Android 项目常见的退出方式有两种一种是弹出dialog对话框提示用户退出应用,下面就两种实现形式有示列代码可以参考:
第一种弹出dialog样式退出方式:
1.第一步首先要监测用户是否按下back键,就要重写onKeyDown()
2.构建dialog
主要代码如下:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event != null && keyCode == event.KEYCODE_BACK) {
alertDialog();
}
return false;
}
private void alertDialog(){
CharSequence charTitle = "退出";
CharSequence charMessage = "您确定退出吗?";
CharSequence [] charSequence = new CharSequence[]{"确定","取消"};
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mActivity)
.setIcon(R.drawable.ic_launcher)//设置头部图片
.setTitle(charTitle)//设置标题
.setMessage(charMessage)//设置提示内容
.setPositiveButton(charSequence[0], new DialogInterface.OnClickListener() {//确定按钮监听
@Override
public void onClick(DialogInterface dialog, int which) {
/**
* 可添加项目处理逻辑
*/
mActivity.finish();
}
})
.setNegativeButton(charSequence[1], new DialogInterface.OnClickListener() {//取消按钮监听
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
效果如下:
第二种双击两次back键退出样式
主要代码如下:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event != null && keyCode == event.KEYCODE_BACK) {
exitApp();
}
return false;
}
/**
* 双击退出应用
*/
private boolean isExit = false;
private void exitApp(){
if (isExit == false) {
isExit = true;
Toast.makeText(mActivity, "再按一下退出", Toast.LENGTH_LONG).show();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
isExit = false;
}
}, 2000);
}else{
mActivity.finish();
}
}
效果图如下:
另一种实现方式:
@Override
public void onBackPressed() {
if(backToFinish())finish();
}
/**
* 双击退出
*/
private int BACK = 0;
private boolean backToFinish(){
if(BACK==0){
BACK++;
Toast.makeText(mActivity,"再按一次退出", Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1500);
BACK--;
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
return false;
}else if(BACK==1){
return true;
}
return true;
}
内容很简单,希望对你有所帮助!
标签:
原文地址:http://www.cnblogs.com/shishoufeng/p/4583957.html