首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当应用程序处于后台时启动后台服务

当应用程序处于后台时启动后台服务
EN

Stack Overflow用户
提问于 2022-04-01 12:40:45
回答 1查看 157关注 0票数 0

当我们收到通知时,如何使用后台服务启动警报?当我的应用程序处于活动状态时,后台服务就很容易启动,但是当应用程序处于后台时,后台服务就无法运行。

EN

回答 1

Stack Overflow用户

发布于 2022-05-08 12:35:11

1.为什么会发生这种情况?

FCM (Firebase Cloud messages )中有两种类型的消息:

显示消息:这些消息只有在应用程序处于前台时才触发onMessageReceived()回调

foreground/background/killed数据消息:即使应用程序在中,数据消息也会触发onMessageReceived()回调

代码语言:javascript
复制
override fun onMessageReceived(remoteMessage: RemoteMessage) {
    // ...

    // TODO(developer): Handle FCM messages here.
    // Not getting messages here? See why this may be:
    Log.d(TAG, "From: ${remoteMessage.from}")

    // Check if message contains a data payload.
    if (remoteMessage.data.isNotEmpty()) {
        Log.d(TAG, "Message data payload: ${remoteMessage.data}")

        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use WorkManager.
            scheduleJob()
        } else {
            // Handle message within 10 seconds
            handleNow()
        }
    }

    // Check if message contains a notification payload.
    remoteMessage.notification?.let {
        Log.d(TAG, "Message Notification Body: ${it.body}")
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71707078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档