检测到将要运行的android应用程序 [英] Detecting android application going to background

查看:620
本文介绍了检测到将要运行的android应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的应用程序进入后台"/变为非活动状态"时,我需要关闭蓝牙.

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

我尝试在MainActivity的onPause()中执行此操作,但由于现在BT消失(Mainactivity的onPause()被触发),所以即使我启动了一个显示所选项目的实体详细信息的新活动,该操作也无法正常工作来自Mainactivity.

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.

我需要的是App的某种"onPause()",而不是一个活动.

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?

推荐答案

将此依赖项拉到build.gradle文件中:

Pull this dependency in your build.gradle file:

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

然后在您的Application类中,使用此:

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");
    }
}

更新您的AndroidManifest.xml文件:

Update your AndroidManifest.xml file:

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

这篇关于检测到将要运行的android应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆