Function called during back button clicks on Android

What function do you call when you press the back button on Android. My requirement is that when the application starts and the user clicks the "Back" button, the application status should be saved in the database, and the user should be able to see the status when he returns to the application.

Browsing over the Internet, I realized that we can process the control using the onKeyDown() function. However, even if I use it in my code, the function is not called when I click the back button. Below is the function:

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) { Log.d(null,"In on Key Down"); if (keyCode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); return true; } return super.onKeyDown(keyCode, event); } 

Please suggest if someone comes across the same / similar scenario.

+4
source share
5 answers

Use Activity lifecycle methods to save and restore state. You can save your state during onPause and restore to onResume. In your activity:

  @Override protected void onPause() { super.onPause(); //Save state here } @Override protected void onResume() { super.onResume(); //Restore state here } 

You can also do this in onStart / onStop. Check out the action lifecycle here: http://developer.android.com/reference/android/app/Activity.html

+6
source

the activity function that is called when the "Back" button is pressed is located in the "On" panel

void onBackPressed () Called when activity detects a key press on the back side.

upvote, if you came here for this, and not specifically for saving state: P

+13
source

You do not need to redefine the behavior of the back button to maintain the status of your activity.

Just override onPause() and save any persistent state you want.

0
source

Save the changes to SharedPreferences and copy the changes to your SQLite databases in onPause . Upload them to onResume .

To save the current state of your activity (for example, which tab the user has open), use onSaveInstance(Bundle outState) and the Bundle passed to you in onCreate (Bundle savedInstanceState) to save and receive this information.

0
source

Change the return to false inside the back condition

 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { Log.d(null,"In on Key Down"); if (keyCode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); return false; } return super.onKeyDown(keyCode, event); 

}

0
source

Source: https://habr.com/ru/post/1344854/


All Articles