如何在应用退出之前配置后退按钮两次?我想触发
@Override
public void onBackPressed() {
//custom actions
//display toast "press again to quit app"
super.onBackPressed();
}
答案 0 :(得分:8)
试试这个:
private boolean doubleBackToExitPressedOnce = false;
@Override
protected void onResume() {
super.onResume();
// .... other stuff in my onResume ....
this.doubleBackToExitPressedOnce = false;
}
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press twice to exit", Toast.LENGTH_SHORT).show();
}
这个片段句柄也是活动恢复时的重置状态
答案 1 :(得分:2)
我看到这个问题有点陈旧但我可能会帮助一些人寻找替代已经给出的答案。
这就是我处理退出应用程序的方法。如果某人有更好的 - 或谷歌建议 - 实现这一目标的方法,我想知道。
编辑 - 忘记提及这是针对Android 2.0及更高版本。对于以前的版本,请覆盖onKeyDown(int keyCode, KeyEvent event)
并检查keyCode == KeyEvent.KEYCODE_BACK
。 Here是查看的好链接。
private boolean mIsBackEligible = false;
@Override
public void onBackPressed() {
if (mIsBackEligible) {
super.onBackPressed();
} else {
mIsBackEligible = true;
new Runnable() {
// Spin up new runnable to reset the mIsBackEnabled var after 3 seconds
@Override
public void run() {
CountDownTimer cdt = new CountDownTimer(3000, 3000) {
@Override
public void onTick(long millisUntilFinished) {
// I don't want to do anything onTick
}
@Override
public void onFinish() {
mIsBackEligible = false;
}
}.start();
}
}.run(); // End Runnable()
Toast.makeText(this.getApplicationContext(),
"Press back once more to exit", Toast.LENGTH_SHORT).show();
}
}
答案 2 :(得分:0)
如果>你可以用全局整数做你想要的事情并计算它。 2,退出。
但你可以采取更好的(IMO)方法,在那里你询问用户是否愿意戒烟:
private void questionQuit(){
final CharSequence[] items = {"Yes, quit now", "No, cancel and go back"};
builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("Are you sure you want to quit?");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0:
quit();
break;
case 1:
default:
break;
}
}
}).show();
AlertDialog alert = builder.create();
}
答案 3 :(得分:0)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK :
int i = 0 ;
if(i == 1 )
{
finish();
}
i++;
return true;
}
}
return super.onKeyDown(keyCode, event);
}