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.
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
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
implementation 'android.arch.lifecycle:extensions:1.1.1'
–
Camper 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
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()
© 2022 - 2024 — McMap. All rights reserved.