我正在使用以下代码作为后退按钮,但如果我按下用户设备的后退按钮,它无法退出应用程序
private Boolean exit = false;
@Override
public void onBackPressed() {
if (exit) {
this.finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
答案 0 :(得分:2)
private Boolean exit = false;
@Override
public void onBackPressed() {
if (exit) {
this.finishAffinity();
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
答案 1 :(得分:0)
使用此...
private long lastBackPressTime = 0;
@Override
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
//Add Snhackbar or Toast, whatever you want
this.lastBackPressTime = System.currentTimeMillis();
} else {
if (toast != null) {
toast.cancel();
}
moveTaskToBack(true);
}
}
答案 2 :(得分:0)
这可能有用。请改用finishAffinity()
。
boolean doubleBackToExitPressedOnce = false;
public void onBackPressed(){
if(doubleBackToExitPressedOnce)
{
finishAffinity();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click back again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
},3500);
}
答案 3 :(得分:0)
保持布尔值toClose = false; 并且在onBackPressed()方法中使用此代码
if (toClose)
super.onBackPressed();
else
{
toClose=true;
Utils.showToast(context,getString(R.string.back_again));
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
toClose=false;
}
},2000);
}
答案 4 :(得分:0)
像这样更改你的代码。
private Boolean exit = false;
@Override
public void onBackPressed() {
if (exit) {
this.finishAffinity();
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
答案 5 :(得分:0)
这对你有用 全局定义
private boolean doubleBackToExitProceed = false;
@Override
public void onBackPressed() {
if (doubleBackToExitProceed) {
finish();
return;
}
doubleBackToExitProceed = true;
Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitProceed = false;
}
}, 2000);// time in milliseconds.
}
答案 6 :(得分:0)
使用它可以在按下后退按钮时关闭应用程序。
@Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}