应用程序需要定期(15-30 分钟)与后端进行数据同步。 我使用 WorkManager API 实现了这一点,但遇到了同步仅在应用程序运行时触发的问题;如果用户或 Android 操作系统终止应用程序,我的同步工作线程将停止工作。 同时,我发现即使我终止进程,同步也会在模拟器上运行。
我已经阅读了很多有关此主题的信息,但看不出我有任何错误。
您能告诉我可能是什么问题吗?
我的测试工作人员(将日志写入文件):
class TestWorker
(appContext: Context, params: WorkerParameters) :
CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
Timber.d("Message from worker")
return Result.success()
}
}
我的应用程序(启动同步工作线程):
@HiltAndroidApp
@Singleton
class WorkTestApp : Application() {
override fun onCreate() {
super.onCreate()
val fileLogger = FileLogger(context = this)
val reportingTree = ReportingTree(fileLogger)
Timber.plant(reportingTree)
val periodicWorkRequest = PeriodicWorkRequestBuilder<TestWorker>(
repeatInterval = 15,
repeatIntervalTimeUnit = TimeUnit.MINUTES
).build()
val workManager = WorkManager.getInstance(this)
workManager.enqueueUniquePeriodicWork(
"SYNC_WORK_NAME",
ExistingPeriodicWorkPolicy.KEEP,
periodicWorkRequest
)
}
}
应用程序清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:name=".WorkTestApp"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WorkerTest"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.WorkerTest">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
在一些真实设备上,一些制造商安装了非常蹩脚的电池管理应用程序,基本上会杀死所有后台进程。可能这种行为正在影响您的应用程序。
请参阅 dontkillmyapp.com 如果制造商提供该功能,您可能可以指示用户将您的应用程序列入白名单。
我已经构建了问题中的代码(我认为我删除了 Timber 的使用并使用标准 Log 语句来简化事情,以及使用 UPDATE 策略)。然后在非小米设备上进行了测试,我相信该设备没有制造商安装任何愚蠢的电池管理软件
当应用程序在后台甚至手机进入睡眠状态时,它每 15 分钟触发一次
这说明是小米手机的问题,而不是你的代码问题。