8

How to detect when an Android app goes to the background? onPause() or onUserLeaveHint() works but are also called when the orientation is changed or another activity is presented.

DoruChidean
  • 7,941
  • 1
  • 29
  • 33
Agshin Huseynov
  • 170
  • 3
  • 13
  • Possible duplicate of [Determining the current foreground application from a background task or service](http://stackoverflow.com/questions/2166961/determining-the-current-foreground-application-from-a-background-task-or-service) – Aman Grover Sep 22 '16 at 12:49

3 Answers3

17

The marked answer is a workaround for the OP's question. For the rest of us that are looking for an answer you can achieve this using Android Architecture Components

import android.arch.lifecycle.LifecycleObserver;

class OurApplication extends Application implements LifecycleObserver {

    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onAppBackgrounded() {
        Logger.localLog("APP BACKGROUNDED");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppForegrounded() {
        Logger.localLog("APP FOREGROUNDED");
    }
}

and remember to update the manifest file. set the android:name=".OurApplication" attribute for the <application> tag

DoruChidean
  • 7,941
  • 1
  • 29
  • 33
  • Add below dependency for some one who can't use **androidx**: `implementation 'android.arch.lifecycle:extensions:1.1.1'` – MHSaffari Feb 02 '21 at 10:25
3

If orientation changes the app will call through the life cycle once again that means from oncreate

you can avoid it as well by writing the following to code to the manifest

 <activity
      android:name=""
      android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
      android:label="@string/app_name" />

this tell the system that when orientation changes or keyboardHidden or screenLayout changes I will handle it by myself no need to re create it.

then write your code on on pause

Joyal C Joseph
  • 290
  • 2
  • 12
2

Try this

 @Override
    protected void onUserLeaveHint() 
   { 
        // When user presses home page
        Log.v(TAG, "Home Button Pressed");
        super.onUserLeaveHint();
    }

For detail : https://developer.android.com/reference/android/app/Activity.html#onUserLeaveHint()

Ram Prakash Bhat
  • 1,308
  • 12
  • 21
  • 1
    I need finish activity when app goes to the background. onUserLeaveHint also called when orientation changed. So it doesn't works for me – Agshin Huseynov Sep 22 '16 at 16:21