检测 Android 应用程序恢复和暂停状态

Detect Android Application Resume and Pause state

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

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

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

你应该使用 ProcessLifecycleOwner.

Class that provides lifecycle for the whole application process.

You can consider this LifecycleOwner as the composite of all of your Activities, except that ON_CREATE will be dispatched once and ON_DESTROY will never be dispatched. Other lifecycle events will be dispatched with following rules: ProcessLifecycleOwner will dispatch ON_START, ON_RESUME events, as a first activity moves through these events. ON_PAUSE, ON_STOP, events will be dispatched with a delay after a last activity passed through them. This delay is long enough to guarantee that ProcessLifecycleOwner won't send any events if activities are destroyed and recreated due to a configuration change.

It is useful for use cases where you would like to react on your app coming to the foreground or going to the background and you don't need a milliseconds accuracy in receiving lifecycle events.

实施

步骤 1. 创建一个名为 MyApp 的 class 扩展自应用程序 class.

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. 将 class 添加到 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>