当用户双击硬件返回按钮时,我试图退出我的应用程序,我在应用程序中使用了以下代码:
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);
在这里,当用户双击硬件返回按钮时,相同的活动一次又一次地出现,但应用程序没有退出。你能帮我解决这个问题吗
尝试如下:
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();
}
源在Oncreate之外的任何地方尝试这个方法,为我工作
@Override
public void onBackPressed()
{
try
{
//pop up Window closed.
if (doubleBackToExitPressedOnce)
{
super.onBackPressed();
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);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
首先,创建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();
}
}