在特定时间运行方法,无需重复

时间:2020-03-31 16:16:06

标签: android android-studio kotlin alarmmanager handler

我需要在特定时间调用Web API,而无需重复。我使用AlarmManager,但从未触发。我还实现了handler.postDelayed,但它会重复。我不知道如何正确实现它。

这是我的alarmManager:

 alarmManager = (getCTX()?.getSystemService(Context.ALARM_SERVICE)) as (AlarmManager)

        var intent: Intent = Intent(getCTX(), NextLiveReceiver::class.java)


        intent.putExtra("next", next)
        intent.putExtra("curTime", curTime)

        myPendingIntent =
            PendingIntent.getBroadcast(
                getCTX(),
                0,//next.toInt(),
                intent,
                0
            )

        var ALARM_TYPE = AlarmManager.RTC_WAKEUP

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            alarmManager.setExactAndAllowWhileIdle(ALARM_TYPE, next, myPendingIntent);
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
            alarmManager.setExact(ALARM_TYPE, next, myPendingIntent);
        else
            alarmManager.set(ALARM_TYPE, next, myPendingIntent)

这是AlarmManagerReceiver:

class NextLiveReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {

            var next: Long = intent.getLongExtra("next", 0)
            var current: Long = intent.getLongExtra("curTime", 0)

            if (next > 0 && current > 0) {

                EventBus.send(NextEvent(true, next, current))
            }

    }
}

这是我的处理程序:

 var handler: Handler = Handler()
        handler.postDelayed({

            viewModel.fetchLiveInfo(viewModel.currentChannelId.value!!, next, 0)
        }, delay)

        handler.removeCallbacks(null)

1 个答案:

答案 0 :(得分:0)

WorkManager,Handler和AlarmManager未能按我预期的方式工作。因此,我以 Kotlin延迟的方式解决了该问题:

  runBlocking {
                                scope.launch(Dispatchers.Main + handler) {
                                    Timber.i("--Launch-- start : ${getUnixTime()}")
                                    delay(delayTime)

                                    removeRate()
                                    refetchLiveInfo(channelId, liveInfoResult[0].next, 1)
                                    Timber.i("--Launch-- ended : ${getUnixTime()}")
                                }

                            }