当用户双击HardWare后退按钮时,我试图退出我的应用程序,我在我的应用程序中使用了以下代码:
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
Dashboard_Activity.this.finish();
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;
}
}, 2000);
此处,当用户双击硬件后退按钮时,同一活动会一次又一次出现,但应用程序不会退出。你能帮我解决这个问题。
答案 0 :(得分:0)
尝试以下方法:
private static long back_pressed;
@Override
public void onBackPressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
答案 1 :(得分:0)
尝试此方法您的代码在Oncreate的任何位置,为我工作
getMainActivity().getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO | ActionBar.DISPLAY_HOME_AS_UP);
ActionBar ab = getMainActivity().getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
答案 2 :(得分:0)
首先,创建 SplashScreenActivity :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish();
}
然后在您的活动中(或在BaseActivity中)将此变量添加为类成员:
private long milis;
并覆盖 onBackPressed():
@Override
public void onBackPressed() {
if(milis + 2000 > System.currentTimeMillis()){
Intent intent = new Intent(this, SplashScreenActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else{
milis = System.currentTimeMillis();
}
}