首页 > 解决方案 > CountDownTimer onTick 在服务中不起作用

问题描述

我正在尝试创建一个带有倒数计时器的 android 应用程序小部件。我有一个发出 HTTP 请求的服务,然后是一个倒计时计时器,它更新应用程序小部件的 UI(使用来自 HTTP 请求的数据)。无论出于何种原因,倒数计时器 onTick 都不会在服务内部计时。我没有收到任何错误..

这是我的代码:

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {

    val request = Request.Builder()
            .url("URL_TO_CALL")
            .build()

    //Make API call
    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {}
        override fun onResponse(call: Call, response: Response) {

            if (Looper.myLooper() == null) {
                Looper.prepare()
                Looper.loop()
            }


            //Create countdown timer object
            var ctd = object : CountDownTimer(countdownTime, 5000) {

                override fun onTick(millisUntilFinished: Long) {
                    //Nothing in here is being called

                }

            }

            Handler().postDelayed({
                ctd.start()
            }, 500)

        }
})

return Service.START_STICKY

}

标签: androidkotlinandroid-service

解决方案


你有没有放入WAKE_LOCK?

private PowerManager.WakeLock mWakeLock = null;
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        mWakeLock.acquire();

并在 onDestroy

if (mWakeLock != null && mWakeLock.isHeld()) {
            mWakeLock.release();
        }

现在,这是如果您关闭屏幕时您的应用程序正在关闭


推荐阅读