所以我有一个工作人员,它必须在计划的第二天开始运行。因此,如果工作在今天晚上8点激活,那么我需要在第二天9 AM执行工作。因此,我将OneTimeWorkRequest
与setInitialDelay()
一起使用。
这是代码
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)
但是我检查了一下,第二天醒来时工作没有执行。 为什么不预定?我计算第二天的时间戳的方式有问题吗?
答案 0 :(得分:0)
我们在Google的问题跟踪器中看到here:
不幸的是,某些设备实施了从“最近”菜单中杀死应用程序的强制停止操作。 Stock Android不会执行此操作。当应用程序被强制停止时,它无法执行作业,接收警报或广播等。因此,不幸的是,我们无法解决这个问题-问题出在操作系统上,没有解决方法。
因此,您需要Service
才能保持应用程序的生命周期。同样,Service
终止时(不管是什么原因),它都应该重新启动并初始化您的工作程序,以确保其执行并保持工作程序活着。这是使用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)
}
}
Manifest.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>