Android - How To Override the "Back" button so it doesn't Finish() my Activity?

AndroidAndroid ActivityNullpointerexceptionBack ButtonOnkeypress

Android Problem Overview


I currently have an Activity that when it gets displayed a Notification will also get displayed in the Notification bar.

This is so that when the User presses home and the Activity gets pushed to the background they can get back to the Activity via the Notification.

The problem arises when a User presses the back button, my Activity gets destroyed but the Notification remains as I want the user to be able to press back but still be able to get to the Activity via the Notification. But when a USER tries this I get Null Pointers as its trying to start a new activity rather than bringing back the old one.

So essentially I want the Back button to act the exact same as the Home button and here is how I have tried so far:


		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event)  {
		    if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
		            && keyCode == KeyEvent.KEYCODE_BACK
		            && event.getRepeatCount() == 0) {
		    	Log.d("CDA", "onKeyDown Called");
		        onBackPressed();
		    }

		    return super.onKeyDown(keyCode, event);
		}

		public void onBackPressed() {
			Log.d("CDA", "onBackPressed Called");
	        Intent setIntent = new Intent(Intent.ACTION_MAIN);
	        setIntent.addCategory(Intent.CATEGORY_HOME);
	        setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        startActivity(setIntent); 
			
		    return;
		}	

However the above code still seems to allow my Activity to be destroyed, How can I stop my Activity from being destroyed when the back button is pressed?

Android Solutions


Solution 1 - Android

Remove your key listener or return true when you have KEY_BACK.

You just need the following to catch the back key (Make sure not to call super in onBackPressed()).

Also, if you plan on having a service run in the background, make sure to look at startForeground() and make sure to have an ongoing notification or else Android will kill your service if it needs to free memory.

@Override
public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   setIntent.addCategory(Intent.CATEGORY_HOME);
   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(setIntent);
}

Solution 2 - Android

It was easier to implement it only with one line of code:

@Override
public void onBackPressed() {
   moveTaskToBack(true);
}

Solution 3 - Android

simply do this..

@Override
public void onBackPressed() {
    //super.onBackPressed();
}

commenting out the //super.onBackPressed(); will do the trick

Solution 4 - Android

I think what you want is not to override the back button (that just doesn't seem like a good idea - Android OS defines that behavior, why change it?), but to use the Activity Lifecycle and persist your settings/data in the onSaveInstanceState(Bundle) event.

@Override
onSaveInstanceState(Bundle frozenState) {
    frozenState.putSerializable("object_key",
        someSerializableClassYouWantToPersist);
    // etc. until you have everything important stored in the bundle
}

Then you use onCreate(Bundle) to get everything out of that persisted bundle and recreate your state.

@Override
onCreate(Bundle savedInstanceState) {
    if(savedInstanceState!=null){ //It could be null if starting the app.
        mCustomObject = savedInstanceState.getSerializable("object_key");
    }
    // etc. until you have reloaded everything you stored
}

Consider the above psuedo-code to point you in the right direction. Reading up on the Activity Lifecycle should help you determine the best way to accomplish what you're looking for.

Solution 5 - Android

Try this:

@Override
public void onBackPressed() {
    finish();
}

Solution 6 - Android

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();
        }
    }    
}

Solution 7 - Android

@Override
public void onBackPressed() {
// Put your code here.
}

//I had to go back to the dashboard. Hence,

@Override
public void onBackPressed() {
    Intent intent = new Intent(this,Dashboard.class);
    startActivity(intent);
}
Just write this above or below the onCreate Method(within the class)

Solution 8 - Android

In Kotlin:

val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
    // Handle the back button event
}

For more information you can check this.

There is also specific question about overriding back button in Kotlin.

Solution 9 - Android

Looks like im very late but for those of you who need to switch to new screen and clear back button stack here is a very simple solution.

startActivity(new Intent(this,your-new-screen.class));
finishAffinity();

The finishAffinity(); method clears back button stack.

Solution 10 - Android

just do this

@Override
public void onBackPressed() {
    super.onBackPressed();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDonal RaffertyView Question on Stackoverflow
Solution 1 - AndroidekawasView Answer on Stackoverflow
Solution 2 - AndroidTeo InkeView Answer on Stackoverflow
Solution 3 - AndroidandroCoder-BDView Answer on Stackoverflow
Solution 4 - AndroidkiswaView Answer on Stackoverflow
Solution 5 - AndroidThakurView Answer on Stackoverflow
Solution 6 - AndroidFerran MaylinchView Answer on Stackoverflow
Solution 7 - Androiduser3156040View Answer on Stackoverflow
Solution 8 - AndroidsolazaView Answer on Stackoverflow
Solution 9 - AndroidRK_DUDE02View Answer on Stackoverflow
Solution 10 - AndroidTasos FourlakisView Answer on Stackoverflow