Detecting android application going to background

Petr B picture Petr B · Dec 9, 2013 · Viewed 22.3k times · Source

I need to turn off Bluetooth when my app "goes to background"/"becomes inactive".

I tried to do it in onPause() of my MainActivity but that doesn't work since now BT goes off (onPause() of the Mainactivity is fired) even when I start a new activity showing an entity detail of chosen item from the Mainactivity.

What I need is some kind of "onPause()" of my App not of a single activity.

I think nothing like this exists so is there any preferable solution?

Answer

Sachin Upreti picture Sachin Upreti · May 17, 2018

Pull this dependency in your build.gradle file:

dependencies {
    implementation "android.arch.lifecycle:extensions:1.1.1"
}

Then in your Application class, use this:

public class MyApplication extends Application implements LifecycleObserver {

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

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onAppBackgrounded() {
        Log.d("MyApp", "App in background");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onAppForegrounded() {
        Log.d("MyApp", "App in foreground");
    }
}

Update your AndroidManifest.xml file:

<application
    android:name=".MyApplication"
    ....>
</application>