- 我首先在 MainActivity 的 oncreate 里调用了
val intent =Intent(this,MyService::class.java) startForegroundService(intent)启动了服务 - 又在 MyService 里的 onStartCommand 中调用了以下函数
val job = Job()
val mCoroutineScope = CoroutineScope(job)
val notification = NotificationCompat.Builder(service, "1")
.setContentTitle("test")
.setSmallIcon(R.drawable.ic_action_name)
.setAutoCancel(true)
startForeground(1,notification.setContentText("")
.build())
stopForeground(true)
最后创建了一个协程,在协程中从服务器获取最新消息并通知 具体过程如下:
mCoroutineScope.launch{
while(true)
{
val content = 从网络中获取消息
val notfi = notification.setContentText(content)
.setContentIntent(pending)
.build()
notificationManager.notify(id, notfi)
}
}
我的问题是: 启动服务后,把 app 拉到了后台,当服务运行一会后,消息就不会再弹出,就需要再次进入 app 界面,消息又开始弹出,如此往复。并不能像微信那样拉到后台后,后台服务不会暂停,消息会及时的弹出。