Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting android application going to background

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?

like image 993
Petr B Avatar asked Dec 09 '13 11:12

Petr B


2 Answers

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>
like image 91
Sachin Upreti Avatar answered Nov 10 '22 01:11

Sachin Upreti


To detect that application is going to background, Override following method in Application class of your App :

@Override
public void onTrimMemory(int level) {
    super.onTrimMemory(level);
    if(level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN)
        //called when app goes to background
}
like image 43
Tarun Deep Attri Avatar answered Nov 10 '22 00:11

Tarun Deep Attri