Onbackpressed to Hide Not Destroy Activity

onBackPressed to hide Not destroy activity

If you want to mimic the "Home" button on specific Activities just do this:

Below API 5:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}

Above and on API 5:

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

It will move the Task to background.. when you return, it will be as it was.

You can see more information about this here: Override back button to act like home button

How not to destroy activity in onBackPressed?

If you want to customize the behaviour of your buttons, you have to use in your activity ...

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){

return true; //To assess you have handled the event.
}
//If you want the normal behaviour to go on after your code.
return super.onKeyDown(keyCode, event);
}

Here is some more information about handling key event.


Although it seems what you want to do is just retain the state of your activity. The best way is to store your data before quitting and call it back when you recreate your activity.

If you want to store temporary data (I mean not save it between 2 boots), one way to do it would be to use sharedPreferences.

//Before your activity closes
private val PREFS_NAME = "kotlincodes"
private val SAVE_VALUE = "valueToSave"
val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putInt(SAVE_VALUE, value)
editor.commit()

//When you reopen your activity
private val PREFS_NAME = "kotlincodes"
val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
sharedPref.getString(SAVE_VALUE, null)

Another way to do it since you cannot use sharedPreferences (because you don't use primitive types), is to use a global singleton.

Here is a Java implementation ...

public class StorageClass{
private Object data1 = null;
private StorageClass instance;

private StorageClass(){};

public static final StorageClass getInstance(){
if(instance == null){
synchronized(StorageClass.class){
if(instance==null) instance = new StorageClass();
}
}
return instance;
}

public void setData1(Object newData) { data1 = newData; }

public Object getData1() { return data1; }
}

Then just use ...

StorageClass.getInstance().setData1(someValue);

... and ...

StorageClass.getInstance().getData1(someValue);

In Kotlin ...

object Singleton{
var data1
}

Which you use with ...

Singleton.data1 = someValue    //Before closing.
someValue = Singleton.data1 //When restarting the activity.

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

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

Detect if onBackPressed will destroy an Activity?

Instead of handling back button pressing in your activity, you could do it in your fragments like this:

activity?.onBackPressedDispatcher?.addCallBack(viewLifecycleOwner, true){
//Navigate to other fragment
}

just implement Fragment ktx dependency

implementation "androidx.fragment:fragment-ktx:1.2.5"

For further information, check out this

How to make an activity stop, rather then be destroyed, from the BACK key?

Why is it that you need to keep the variables alive? Given the established lifecycle of an Android application, I'm not sure that preventing the activity from being destroyed "just to keep the variables" makes sense.

  1. Even if you stop the application without destroying it, there is always the chance that Android will kill it to free up memory. You will have to account for this in your code anyway, and so preventing the application from destroying doesn't save you from writing code.

  2. Variables can be saved and restored relatively easily and quickly using SharedPreferences in your onPause() and onResume() methods. Unless you are storing a ton of data, preventing the application from destroying might not make much of a difference.

  3. It sounds like you want to keep the variables in memory because you intend to return to this activity. Typically, you don't use the back button to navigate away from activities that you intend to come back to. Instead you would create an Intent and start a new activity. When you do this, Android places the current activity on the Back Stack calling onPause() and onStop(), which seems like exactly the sort of behavior you are looking for.

So if you still really want to prevent your activity from being destroyed (at least until Android decides it's using too much memory and kills it on it's own) you could always use Sagar's code and start a new activity in onBackPressed().

@Override
public void onBackPressed()
{
Intent intent = new Intent(this, Other.class);
startActivity(intent);
}

Just be certain that that is what you really want to do.

Hiding an Activity and Showing it android

Ciril answer is correct to some extent. Because by overridding onBackPressed we came back to previous activity without finishing it. But it is not final , if android need resources , it can delete it. I don't find a way to avoid deleting it. but my app is working fine . And main thing is to call the Activity which may be down in the stack and opening that particular activity is must.

The code to open an activity from stack and reorder it to top of stack is..

Intent intent = new Intent(Album.this, StaticAudioPlayer.class);

intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);// this flag reorder the activity to top
startActivity(intent);

Do not destroy android activity and should not be in the history

Do not use special launch modes for this!

MainActivity should call ActivityB like this:

Intent intent = new Intent(this. ActivityB.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

ActivityB should call MainActivity like this:

Intent intent = new Intent(this. MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

This will allow you to flip back and forth between the 2 activities, without creating any new instances. You will need to override onBackPressed() in one or both activities.

If you want the BACK button in MainActivity to exit the app, you will need to be a bit tricky. An easy way to do this is as follows:

Declare a static variable in MainActivity like this:

public static boolean exit = false;

in MainActivity.onBackPressed(), do the following:

exit = true;
super.onBackPressed();

This will cause MainActivity to finish. If MainActivity is the only active Activity, then you are done. However, it is possible that ActivityB is underneath MainActivity. To force ActivityB to finish in this situation, add this to ActivityB.onResume():

super.onResume();
if (MainActivity.exit) {
finish();
return;
}
// Rest of onResume() code goes here...

How to completely destroy activity on back pressed?

I noticed that the variables I defined in the second activity, is saving their values (that I changed in activity) through back stack and even closing application wouldn't delete them.

The variables :

static int mcurchoice ;
static int mcurtab ;

I solved my problem by setting them to 0 in onBackPressed() method :

mcurchoice = 0;
mcurtab = 0;

can someone explain in comments how they will save their values through activity's destroy .?

Not to call onDestroy on onBackPressed

public boolean onKeyDown(int keyCode, KeyEvent event)  
{

if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{

this.moveTaskToBack(true);
return true;
}

return super.onKeyDown(keyCode, event);
}


Related Topics



Leave a reply



Submit