返回键无法正常工作

Back Key not working properly

我想在我的应用程序中添加后退键,所以我添加了这个

onCreate(){
        getActionBar().setDisplayHomeAsUpEnabled(true);
}

还有这个

        if(id == android.R.id.home){
            this.finish();
            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(intent);
        }

当我从应用程序中按下后退按钮时,它工作正常但是当我按下物理后退按钮时,它会终止应用程序

back 按钮和 up 按钮有区别。在您的 post 中,您提到了 up 按钮。参见 Up vs Back in android documentation. For handling the back key, You might need to override onBackPressed() in your activity to handle the situation. See How to handle back button in activity

覆盖这个,

@Override
public void onBackPressed(){
    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
    startActivity(intent);
    finish();
}