1

I want to do a certain thing in my activity's fragment's onresume, but only if Back button has been pressed, and not if the app has been hidden behind another activity or "minimized" using "home" button/

How can I do that

Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180

3 Answers3

1

onPause() will be called when the Activity is moved to the background. onPause() is where you deal with the user leaving your activity. See the diagram here.

If another Activity comes in onPause() is called. You can override onPause(). You can do anything/save anything there. When the activity again comes into foreground onResume() is called. You can override that also, and restore anything there.

@Override
public void onPause() {
super.onPause();  // Always call the superclass method first

// Release the Camera because we don't need it when paused
// and other activities might need to use it.
if (mCamera != null) {
    mCamera.release()
    mCamera = null;
}
}
@Override
public void onResume() {
super.onResume();  // Always call the superclass method first

// Get the Camera instance as the activity achieves full user focus
if (mCamera == null) {
    initializeCamera(); // Local method to handle camera init
}
}

For Back Button see this.

Community
  • 1
  • 1
Mohammed Ali
  • 2,758
  • 5
  • 23
  • 41
  • I know that. onPause is called if the user clicks hardware or actionbar "Back" button OR if they hold Home button, or if another app's activity gets on front. I only want to do a certain thing if the user has invoked onPause by hitting the Home button and not the back buttons – Kaloyan Roussev Nov 17 '14 at 13:43
  • I know I can override it, but how do I detect whether its coming from the back button or the home button – Kaloyan Roussev Nov 17 '14 at 13:50
  • for home button see answer here: http://stackoverflow.com/questions/8881951/detect-home-button-press-in-android also see the links in that answer. This no longer works as of 4.0. – Mohammed Ali Nov 17 '14 at 13:54
  • http://stackoverflow.com/questions/6413700/android-proper-way-to-use-onbackpressed – Mohammed Ali Nov 17 '14 at 13:57
0

The onBackPressed method is available from your Activity. Passing this to your Fragment could be done through a Broadcast, or possibly an Event bus (I'd recommend Otto for this). That way, your Activity can notify your Fragment of the onBackPressed call.

Alex Kolpa
  • 187
  • 1
  • 4
0

You can do it easily: just use a variable in your sharedPreference and toggle it in onBackPressed in your activity to separate it from other actions that may cause onPause, then in onResume reset it :)

M. Erfan Mowlaei
  • 1,376
  • 1
  • 14
  • 25