首页 > 解决方案 > 检测 Android 应用程序恢复和暂停状态

问题描述

我想在应用程序恢复时启动 ScheduledExecutorService 并希望在应用程序暂停时停止。

我只是通过维护计数来检测活动运行状态来找到解决方案。就像在 lib https://github.com/curioustechizen/android-app-pause/tree/master/android-app-pause中一样。

是否有任何其他解决方案来检测应用程序暂停和恢复状态?

标签: androidandroid-lifecycle

解决方案


您应该使用ProcessLifecycleOwner

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

您可以将此 LifecycleOwner 视为所有活动的组合,但 ON_CREATE 将被调度一次,而 ON_DESTROY 将永远不会被调度。其他生命周期事件将按照以下规则分派: ProcessLifecycleOwner 将分派 ON_START、ON_RESUME 事件,因为第一个活动在这些事件中移动。ON_PAUSE,ON_STOP,事件将在最后一个活动通过它们后延迟调度。此延迟足够长,以保证 ProcessLifecycleOwner 在活动因配置更改而被销毁和重新创建时不会发送任何事件。

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

执行

步骤 1.创建一个MyApp从 Application 类扩展命名的类。

public class MyApp extends Application {

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

    private static final class ProcessLifecycleObserver implements LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        public void onApplicationResumed() {
            // Start ScheduledExecutorService here
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        public void onApplicationPaused() {
            // Stop ScheduledExecutorService here
        }
    }
}

步骤 2.将类添加到AndroidManifest.xml文件中

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

    <application
        android:name=".MyApp"
        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>

推荐阅读