gpt4 book ai didi

android - 工作管理器不使用 setInitialDelay 安排工作

转载 作者:太空狗 更新时间:2023-10-29 13:46:33 25 4
gpt4 key购买 nike

所以我有一个 Worker 必须在预定的第二天运行。因此,如果工作在今天晚上 8 点激活,那么我需要在第二天早上 9 点执行工作。所以我将 OneTimeWorkRequestsetInitialDelay() 一起使用。

这是代码

val currentTime = System.currentTimeMillis()
// calculate the timestamp for next dat 9AM
val calendar = Calendar.getInstance()

calendar.set(Calendar.HOUR_OF_DAY, 9)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
// next day
calendar.add(Calendar.DAY_OF_MONTH, 1)

val tomorrowTime = calendar.timeInMillis
val timeDiffBetweenNowAndTomorrow = tomorrowTime - currentTime

Timber.i("Tomorrow date is ${calendar.timeInMillis}")
Timber.i("Difference between now and tomorrow ${timeDiffBetweenNowAndTomorrow}")

val randomWorkRequest = OneTimeWorkRequestBuilder<RandomWallpaperWorker>()
.setInitialDelay(timeDiffBetweenNowAndTomorrow, TimeUnit.MILLISECONDS)
.build()

WorkManager.getInstance().enqueue(randomWorkRequest)

但是我查了一下,第二天醒来的时候,工作并没有执行。为什么不安排呢?我计算第二天时间戳的方式有问题吗?

最佳答案

如我们所见here在 Google 的问题跟踪器中:

Unfortunately, some devices implement killing the app from the recents menu as a force stop. Stock Android does not do this. When an app is force stopped, it cannot execute jobs, receive alarms or broadcasts, etc. So unfortunately, it's infeasible for us to address it - the problem lies in the OS and there is no workaround.

因此,您需要一个Service 来维持您的应用程序。此外,当 Service 终止时(不管是什么原因),它应该重新启动并初始化您的 worker 以确保其执行并保持 worker 任务处于 Activity 状态。下面是使用 STICKY IntentService 实现这个想法。

WallpaperService.kt

import android.app.IntentService
import android.app.Service
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import java.util.*
import java.util.concurrent.TimeUnit

class WallpaperService : IntentService("WallpaperService") {

override fun onHandleIntent(intent: Intent?) {
intent?.apply {
when (intent.action) {
ACTION_SETUP_WORKER -> {
setupWorker()
}
}
}
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
// Define service as sticky so that it stays in background
return Service.START_STICKY
}

private fun setupWorker() {
val calendar = Calendar.getInstance()
val currentTime = calendar.timeInMillis

// for removing from recent apps test
// calendar.add(Calendar.SECOND, 10)

calendar.set(Calendar.HOUR_OF_DAY, 9)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
calendar.add(Calendar.DAY_OF_MONTH, 1)

val tomorrowTime = calendar.timeInMillis
val timeDiffBetweenNowAndTomorrow = tomorrowTime - currentTime

Log.i("WallpaperService", "************ Tomorrow date is ${calendar.timeInMillis}")
Log.i("WallpaperService", "************ Difference between now and tomorrow $timeDiffBetweenNowAndTomorrow")

val randomWorkRequest = OneTimeWorkRequestBuilder<RandomWallpaperWorker>()
.setInitialDelay(timeDiffBetweenNowAndTomorrow, TimeUnit.MILLISECONDS)
.build()
WorkManager.getInstance().enqueue(randomWorkRequest)
}

companion object {

const val ACTION_SETUP_WORKER = "ACTION_SETUP_WORKER"

fun setupWorker(context: Context) {
val intent = Intent(context, WallpaperService::class.java)
intent.action = ACTION_SETUP_WORKER
context.startService(intent)
}
}

}

RandomWallpaperWorker.kt

import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters

class RandomWallpaperWorker(val context: Context, params: WorkerParameters) : Worker(context, params) {

override fun doWork(): Result {

// Do what you want here...

Log.e("RandomWallpaperWorker", "***************** DONE!" )
WallpaperService.setupWorker(context)
return Result.SUCCESS
}

}

MainActivity.kt

import android.os.Bundle
import android.support.v7.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

WallpaperService.setupWorker(applicationContext)
}

}

list .xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aminography.workerapplication">

<application ... >

...

<service android:name=".WallpaperService" android:enabled="true"/>

</application>

</manifest>

关于android - 工作管理器不使用 setInitialDelay 安排工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53097297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com