代码之家  ›  专栏  ›  技术社区  ›  Sriram R

工作经理没有使用setInitialDelay安排工作

  •  3
  • Sriram R  · 技术社区  · 6 年前

    所以我有一个工人必须从计划的第二天开始工作。因此,如果工作在今天晚上8点激活,那么我需要在第二天上午9点执行工作。所以我用 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)
    

    但我检查了一下,第二天醒来时工作没有执行。 为什么没有预定?我计算第二天时间戳的方法有什么问题吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   aminography    6 年前

    如我们所见 here 在谷歌的问题追踪系统中:

    不幸的是,一些设备通过强制停止来实现从Recents菜单中删除应用程序。股票安卓不这样做。当一个应用程序被强制停止时,它不能执行作业、接收警报或广播等。因此不幸的是,我们无法解决这个问题——问题在于操作系统,没有解决方法。

    因此,您需要 Service 保持应用程序的活动状态。同时当 服务 被终止(不管原因是什么),它应该重新启动并初始化您的工作人员以确保其执行并保持工作人员任务的活动状态。下面是使用 STICKY IntentService .

    墙纸服务.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
        }
    
    }
    

    主活动.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)
        }
    
    }
    

    清单.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>