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?
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>
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
}
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