4

如何像微信那样具有长效的后台消息通知

 2 years ago
source link: https://www.v2ex.com/t/862283
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Android

如何像微信那样具有长效的后台消息通知

  fhj · 3 小时 33 分钟前 · 656 次点击
  • 我首先在 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 界面,消息又开始弹出,如此往复。并不能像微信那样拉到后台后,后台服务不会暂停,消息会及时的弹出。


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK