Just in case you want to handle the behaviour of the back button (at the bottom of the phone) and the home button (the one to the left of the action bar), this custom activity I'm using in my project may help you.
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
/**
* Activity where the home action bar button behaves like back by default
*/
public class BackActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupHomeButton();
}
private void setupHomeButton() {
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onMenuHomePressed();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onMenuHomePressed() {
onBackPressed();
}
}
Example of use in your activity:
public class SomeActivity extends BackActivity {
// ....
@Override
public void onBackPressed()
{
// Example of logic
if ( yourConditionToOverride ) {
// ... do your logic ...
} else {
super.onBackPressed();
}
}
}