应用场景:点击两次Back键退出程序
效果图:
实现原理:onKeyDown()会捕获当前点击事件,如果当前keyCode等于BACK事件值就会执行exit()方法。在exit()方法中,首先判断isExit的值,如果为false的话,则置为true,同时会弹出提示,并在3000毫秒(3秒)后发出一个消息,在Handler中接收到消息后将isExit值还原成false。如果在发送消息间隔的3秒内,再次按了BACK键,则再次执行exit方法,此时isExit的值已为true,则会执行退出程序的方法。
实现步骤:
1、定义一个boolean型的变量,默认值为false
private boolean isExit = false;
2、覆写Activity中onKeyDown()方法
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)// 当keyCode等于退出事件值时
{
exit();
return false;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
3、封装exit()方法
private void exit()
{
if (isExit)
{
// ACTION_MAIN with category CATEGORY_HOME 启动主屏幕
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
System.exit(0);// 使虚拟机停止运行并退出程序
}
else
{
isExit = true;
Toast.makeText(TwoTimesBackActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
mHandler.sendEmptyMessageDelayed(0, 3000);// 3秒后发送消息
}
}
4、创建Handler对象,用来处理消息
Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)//处理消息
{
super.handleMessage(msg);
isExit = false;
}
};
代码如下:
public class TwoTimesBackActivity extends Activity
{
private boolean isExit = false;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)// 当keyCode等于退出事件值时
{
exit();
return false;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
private void exit()
{
if (isExit)
{
// ACTION_MAIN with category CATEGORY_HOME 启动主屏幕
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
System.exit(0);// 使虚拟机停止运行并退出程序
}
else
{
isExit = true;
Toast.makeText(TwoTimesBackActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
mHandler.sendEmptyMessageDelayed(0, 3000);// 3秒后发送消息
}
}
Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)//处理消息
{
super.handleMessage(msg);
isExit = false;
}
};
}