当应用程序在后台或未运行时,推送通知无法正常工作

2024-01-11

我正在使用 Firebase Cloud Messaging 发送推送通知。

这是我的FirebaseMessageService:

public class FireBaseMessageService extends FirebaseMessagingService {


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.e("TAG", "From: " + remoteMessage.getFrom());
    Log.e("TAG", "Notification Message Body: " + remoteMessage.getData().get("CardName")+"  :  "+remoteMessage.getData().get("CardCode"));
    sendNotification(remoteMessage.getNotification().getBody());
}


private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, StartActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher_final)
            .setContentTitle("Notification")
            .setContentText(messageBody)
            .setTicker("Test")
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_SOUND)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

And FirebaseInstanceServer:

public class FirebaseInstanceService extends FirebaseInstanceIdService {


@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.e("TAG", "Refreshed token: " + refreshedToken);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);

}

private void sendRegistrationToServer(String token) {


      // Add custom implementation, as needed.
        Log.e("TAG", "Refreshed token2: " + token);
    }
}

其中声明于AndroidManifest:

<service
    android:name=".util.notifications.FireBaseMessageService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

<service
    android:name=".util.notifications.FirebaseInstanceService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

所以问题是当应用程序运行时ticker显示良好,通知带有默认声音,但是当应用程序在后台或未运行时,通知没有任何声音,并且ticker不显示在状态栏中。
为什么会发生这种情况以及如何解决它?


使用 FCM,您可以指定要发送到的 POST 有效负载https://fcm.googleapis.com/fcm/send。在该有效负载中,您可以指定data or a notification键,或两者兼而有之。

如果您的有效负载仅包含data关键,您的应用程序将自行处理所有推送消息。例如。它们都已交付给您onMessageReceived处理程序。

如果您的有效负载包含notification关键,您的应用程序将自行处理推送消息only如果您的应用程序处于活动状态/在前台。如果不是(因此它在后台,或完全关闭),FCM 会使用您放入的值来处理为您显示通知notification关键有效负载。

请注意,从控制台(例如 Firebase 控制台)发送的通知,它们始终包含notification key.

看起来您想自己处理 FCM 消息,以便您可以更多地自定义通知等,因此最好不要包含notification在 POST 有效负载中键入密钥,以便所有推送消息都会传递到您的onMessageReceived.

你可以在这里读更多关于它的内容:
高级消息传递选项 https://firebase.google.com/docs/cloud-messaging/concept-options
下游消息语法 https://firebase.google.com/docs/cloud-messaging/http-server-ref#send-downstream

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当应用程序在后台或未运行时,推送通知无法正常工作 的相关文章

  • 将 cron 作业配置为在 Jenkins 上每 15 分钟运行一次

    如何在 Jenkins 上每 15 分钟运行一次 cron 作业 这是我尝试过的 在 Jenkins 上 我使用以下 cron 语法设置了每 15 分钟运行一次的作业 14 但该作业每小时执行一次 而不是 15 分钟 我收到有关 cron
  • 为什么没有参数的函数(与实际函数定义相比)可以编译?

    我刚刚看到某人的 C 代码 我很困惑为什么要编译它 有两点我不明白 The 函数原型与实际函数定义相比没有参数 中的参数函数定义没有类型 include
  • iOS HTTP 请求在后台运行

    当应用程序处于后台时 可以向 PHP 服务器发出 HTTP 异步请求吗 该应用程序是基于位置的应用程序 应收集当前位置并每 5 或其他值 分钟将坐标发送到服务器 即使应用程序处于后台 我也可以将 http 帖子发送到服务器吗 我读到了很多关
  • 在 pip 中为 Flask 应用程序构建 docker 映像失败

    from alpine latest RUN apk add no cache python3 dev pip3 install upgrade pip WORKDIR backend COPY backend RUN pip no cac
  • 类型铸造自我

    以下自我转换对 ClassA 有何作用 这种种姓可以让你进入ClassA吗 A h类 interface ClassA NSObject NSUInteger someNumber ClassB classB property nonato
  • Spring - 使用存储过程时使用 simplejdbccall 进行批量更新

    我正在使用 spring jdbc 模板 使用存储过程创建记录 public Long create City obj SimpleJdbcCall jdbcCall new SimpleJdbcCall getJdbcTemplate g
  • 用于高级搜索/过滤的.Net Web API URL 约定

    我对 Microsoft 的 REST 和 WebAPI 比较陌生 我们正在实现一个中心 REST 服务 它将容纳多种类型的对象获取和设置 作为该项目的领导者 我的任务是提出我们正在使用的正确的 Uri 设计 我想知道关于战争什么想法更好
  • 你遇到过哪些 git 陷阱?

    我遇到的最糟糕的情况是 git 子模块 我在 github 上有一个项目的子模块 该项目无人维护 我想提交补丁 但无法提交 所以我分叉了 现在子模块指向原始库 而我需要它指向 fork 因此 我删除了旧的子模块 并将其替换为同一提交中新项目
  • Gitflow错误无法初始化

    我已经将 gitflow 安装在我的 github 项目所在的目录中 但是 当我尝试使用命令 启动时git flow init 我收到以下错误消息 git flow init C cygwin64 usr local bin gitflow
  • 使用Python的timeit获取“全局名称'foo'未定义”

    我想知道执行一条Python语句需要多少时间 所以我上网查了一下 发现标准库提供了一个名为timeit http docs python org library timeit html旨在做到这一点 import timeit def fo
  • 从哪里开始阅读 SQLite 源代码? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我想了解sqlite是如何实现的 并且 想阅读源代码 我已经下载了源代码 我应该开始查看代码的哪一部分 SQLite文档页 http
  • 重构后如何保留 terraform 资源以使用 for_each?

    目前我正在对我们的基础设施进行小型重构 我的项目的当前版本类似于以下内容 我正在尝试使用 for each 来重用变量 resource google cloud scheduler job job name Create All Doss
  • 获取css规则、chrome扩展

    我正在开发 Chrome 扩展程序 它需要访问document styleSheets cssRules 它在某些网站上运行良好 例如w3school 但其他人则不然 比如堆栈溢出 我收到错误 Failed to read the cssR
  • 安装 RVM 时出现问题

    我已按照 rvm 网站上的说明执行了命令 但似乎不起作用 从 git 存储库获取代码运行顺利 但是当我尝试使用时 rvm notes Error usr local bin rvm line 73 home cody rvm scripts
  • 使用 Javascript 删除字符串的最后一个字符

    我有一个DIV与一些字符 如何在每次单击时删除文本中的最后一个字符DIV itself 删除第一个字符 div on click function this text function index text return text repl
  • 构建 OpenCV 时出错 :: MonitorFromRect 未在此范围内声明

    我试图建立OpenCV version 2 4 8与它一起使用CodeBlocks and MinGw 我按照以下指示进行操作here http kevinhughes ca tutorials opencv install on wind
  • AddressAccessDeniedException :无需 netsh 即可解决它?

    我遇到了异常AddressAccessDeniedException因为我的processus没有注册URL的权限 我首先以管理员身份运行我的程序 好的 它成功了 但我现在想要分发我的应用程序 并且我希望每个用户都能够运行它 而不必成为管理
  • 如何在 iOS 11 上的 Swift 中获取 FLAC 文件元数据?

    我需要获取 FLAC 文件的元数据 我尝试了以下代码 let item AVPlayerItem url URL fileURLWithPath path let commonMetadata item asset commonMetada
  • 每组最大 n 个 SQL 查询的高性能方法

    我正在尝试构建一个基础设施 以便根据需要快速运行回归 从包含我们网络服务器上所有历史活动的数据库中提取 apache 请求 为了通过确保我们仍然回归来自较小客户的请求来提高覆盖范围 我想通过为每个客户检索最多 n 个 为了这个问题 假设 1
  • GetActiveObject() 与 GetObject() -- MK_E_UNAVAILABLE 错误

    All 我在将一些 VBA 代码转换为 C 时遇到一些问题 我们有一个充当本地 COM 服务器的第 3 方应用程序 在我们使用的VBA代码中获取对象 获取对现有对象的引用 e g Set appHandle GetObject ProgId

随机推荐