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.
The "onActivityDestroyed" will get called when the app is closed, so if you can check if the app is in background when it is called (so the app is already closed) you can grep exactly the moment when the app is being closed.
An app is running in the background when both the following conditions are satisfied: None of the app's activities are currently visible to the user. The app isn't running any foreground services that started while an activity from the app was visible to the user.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With