android - 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
}
解决方案
你有没有放入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();
}
现在,这是如果您关闭屏幕时您的应用程序正在关闭
推荐阅读
- c - 为什么 scanf("%[^\n]s", ...) 不捕获带空格的字符串?
- r - 使用networkDynamic的base.net大小错误
- string - 使用 io::stdin().read_line 到枚举的字符串导致错误
- windows - 从 tasklist 命令获取 PID
- angular - Angular 路由器:将旧系统 URL 重定向到新 URL
- olap - 如何使用 hdfs 文件创建带有德鲁伊的立方体
- mysql - 将数据从 Excel 数据库返回到 MySQL 数据库
- python - 提出一系列问题并存储在变量中 [Discord.PY]
- arrays - 如何向数组中的现有对象添加新的键和值(Angular)
- java - 如何使用 /oauth/token 端点创建 access_token