android - 检测 Android 应用程序恢复和暂停状态
问题描述
我想在应用程序恢复时启动 ScheduledExecutorService 并希望在应用程序暂停时停止。
我只是通过维护计数来检测活动运行状态来找到解决方案。就像在 lib https://github.com/curioustechizen/android-app-pause/tree/master/android-app-pause中一样。
是否有任何其他解决方案来检测应用程序暂停和恢复状态?
解决方案
您应该使用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>
推荐阅读
- java - 如何从列表中获取字段,并给出一些输入
- java - Java spring 缓存,saveAll 正确处理更新
- php - 我的 php 没有从 ajax 请求将值插入到我的 sql 数据库中
- java - 如何将字符串映射到未知返回类型的java方法引用?
- python - 什么限制会导致这个脚本卡住?
- c# - 在 Avalondock 3.2 中移动选项卡并将其停靠会使程序无响应,直到失去/获得焦点
- r - 有没有办法从 Markdown 文档生成多个报告,但将图像保留在 html 中?
- entity-framework-core - EF 核心中的 DbFunctions.AddSeconds 等效项
- .net-core - .NET Core 3 中是否提供 WPF PresentationFramework.dll?
- git - 带有稀疏结帐的 git 日志过滤器