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 a
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.
just do this
@Override
public void onBackPressed() {
super.onBackPressed();
}
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);
}
It was easier to implement it only with one line of code:
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
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.
@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)