首页 > 解决方案 > 是否可以确定应用程序是否已在屏幕上消失/出现?

问题描述

我想确定我的应用程序是否在屏幕上,即当用户单击主页按钮或锁定屏幕时,我想接收我的应用程序已进入后台的一次性事件。当用户打开我的应用程序或解锁屏幕时,我希望收到该应用程序出现在屏幕上的一次性事件。

Activity的onPauseonResumeonStartonStop方法不是我想要的。当设备屏幕被锁定/解锁时,这些方法被多次调用。有时当屏幕解锁并且我的应用程序在屏幕上时,我会收到onStop / onPause。这对我的用例来说是一个糟糕的场景。当应用打开任何Dialog时调用onWindowFocusChanged。这也是一个糟糕的场景。

是否有另一种变体如何解决问题?

标签: android

解决方案


假设您在项目中使用 AndroidX,那么您可以使用ProcessLifecycleOwner来确定应用程序已经消失或出现在屏幕上。

ProcessLifecycleOwner

为整个应用程序进程提供生命周期的类。

它对于您希望对您的应用程序进入前台或进入后台做出反应并且您在接收生命周期事件时不需要毫秒精度的用例很有用。

在您的代码中使用:

1.创建一个从应用程序类扩展的类。

public class MyApplication extends Application {

    private final MyLifecycleObserver observer = new MyLifecycleObserver();

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

    class MyLifecycleObserver implements LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onAppMoveToForeground() {
            Log.d("MyLifecycleObserver", "My app moves to foreground.");
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onMoveAppToBackground() {
            Log.d("MyLifecycleObserver", "My app moves to background.");
        }
    }
}

2.添加你的AndroidManifest.xmlandroid:name=".MyApplication"文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidx">

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

推荐阅读