我想在申请的简历上启动ScheduledExecutorService,并在申请暂停时停止。
我只有通过保持计数来检测酸化的运行状态才能找到解决方案。就像lib https://github.com/curioustechizen/android-app-pause/tree/master/android-app-pause一样。
是否有其他解决方案来检测应用程序暂停和恢复状态?
发布于 2020-12-07 02:17:26
您应该使用ProcessLifecycleOwner。
类,它为整个应用程序进程提供生命周期。 您可以将此LifecycleOwner视为所有活动的组合,但ON_CREATE将被分派一次,而ON_DESTROY将永远不会被分派。其他生命周期事件将按照以下规则分派:当第一个活动通过这些事件时,ProcessLifecycleOwner将分派ON_START、ON_RESUME事件。ON_PAUSE,ON_STOP,事件将在最后一个活动经过它们之后被延迟地发送。这种延迟足够长,以保证如果由于配置更改而破坏和重新创建活动,ProcessLifecycleOwner不会发送任何事件。 它是有用的用例,当您想要对您的应用程序作出反应,到前台或去背景,你不需要毫秒的准确性,在接收生命周期事件。
Implementation
步骤1.创建一个从应用程序类扩展的名为MyApp的类。
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>https://stackoverflow.com/questions/65168313
复制相似问题