mirror of
https://github.com/pppscn/SmsForwarder
synced 2024-11-08 01:10:23 +00:00
优化:自动任务监控电量——使用hashcode
保证WorkManager
唯一 #458
This commit is contained in:
parent
4e8d8283c2
commit
b80b1f9620
@ -4,6 +4,7 @@ import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.BatteryManager
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.workDataOf
|
||||
@ -62,16 +63,26 @@ class BatteryReceiver : BroadcastReceiver() {
|
||||
//充电状态改变
|
||||
if (isPluggedChanged || isStatusChanged) {
|
||||
Log.d(TAG, "充电状态改变")
|
||||
val request = OneTimeWorkRequestBuilder<BatteryWorker>().setInputData(
|
||||
workDataOf(
|
||||
TaskWorker.CONDITION_TYPE to TASK_CONDITION_CHARGE,
|
||||
"status_new" to statusNew,
|
||||
"status_old" to statusOld,
|
||||
"plugged_new" to pluggedNew,
|
||||
"plugged_old" to pluggedOld,
|
||||
)
|
||||
).build()
|
||||
WorkManager.getInstance(context).enqueue(request)
|
||||
val inputData = workDataOf(
|
||||
TaskWorker.CONDITION_TYPE to TASK_CONDITION_CHARGE,
|
||||
"status_new" to statusNew,
|
||||
"status_old" to statusOld,
|
||||
"plugged_new" to pluggedNew,
|
||||
"plugged_old" to pluggedOld,
|
||||
)
|
||||
// 使用 hashcode 生成唯一的标识符
|
||||
val inputDataHash = inputData.hashCode().toString()
|
||||
// 检查是否已经存在具有相同输入数据的工作
|
||||
val existingWorkPolicy = if (WorkManager.getInstance(context).getWorkInfosByTag(inputDataHash).get().isEmpty()) {
|
||||
ExistingWorkPolicy.REPLACE
|
||||
} else {
|
||||
ExistingWorkPolicy.KEEP
|
||||
}
|
||||
val request = OneTimeWorkRequestBuilder<BatteryWorker>()
|
||||
.setInputData(inputData)
|
||||
.addTag(inputDataHash)
|
||||
.build()
|
||||
WorkManager.getInstance(context).enqueueUniqueWork(inputDataHash, existingWorkPolicy, request)
|
||||
}
|
||||
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user