简介
之前在《人升》的桌面小部件,实现ListView中的点击事件监听的方式是:
使用fillInIntent发送广播到Widget类中,并在onReceive方法中拦截,处理业务逻辑。
但是,
Widget的本质是个广播接收器,不适宜在里面处理耗时操作。
(完成团队事项的时候需要发送网络请求,普通事项需要更改数据库,都可以视为是耗时操作。)
所以,我决定改用IntentService处理完成事项的业务逻辑。
IntentService的特点是后台运行、自动销毁、异步运行。
首先尝试直接用fillInIntent启动服务失败了。
然后改成了先发送广播,然后在Widget类中,并在onReceive方法拦截再启动IntentService:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 
 | override fun onReceive(context: Context, intent: Intent) {super.onReceive(context, intent)
 
 if (...) {
 ...
 } else if (intent.action == FINISH_TASK) {
 
 val finishIntent = Intent(context, FinishTaskIntentService::class.java)
 if (intent.extras != null) {
 finishIntent.putExtras(intent.extras!!)
 }
 
 try {
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
 context.startForegroundService(finishIntent)
 } else {
 context.startService(finishIntent)
 }
 } catch (e: Exception) {
 e.printStackTrace()
 ToastUtils.showShortToast("完成事项似乎出现了一些问题,请尝试刷新下。", LifeUpApplication.getLifeUpApplication())
 }
 }
 }
 
 | 
然后就遇到了坑。