当前位置: 首页 > news >正文

Android Firebase (FCM)推送接入

官方文档:

向后台应用发送测试消息  |  Firebase Cloud Messaging

1、根级(项目级)Gradlegradle的dependencies中添加:

    dependencies {...// Add the dependency for the Google services Gradle pluginclasspath 'com.google.gms:google-services:4.3.10'}

2、模块(应用级)Gradle 中添加 Google 服务插件:

plugins {id 'com.android.application'// Add the Google services Gradle pluginid 'com.google.gms.google-services'...
}
或者
apply {plugin 'com.android.application'// Add the Google services Gradle pluginplugin "com.google.gms.google-services"
}

添加 Firebase Cloud Messaging Android 库的依赖项:(按官方的应该也是可以的)

    implementation(platform("com.google.firebase:firebase-bom:32.3.1"))implementation("com.google.firebase:firebase-analytics-ktx")
//    implementation("com.google.firebase:firebase-auth-ktx")implementation("com.google.firebase:firebase-firestore-ktx")implementation("com.google.firebase:firebase-messaging")// Firebase Cloud Messaging (Kotlin)implementation("com.google.firebase:firebase-messaging-ktx")

3、消息接收

AndroidManifest.xml中添加,接受类

        <serviceandroid:name=".BillionFirebaseMessagingService"android:exported="true"><intent-filter><action android:name="com.google.firebase.MESSAGING_EVENT" /></intent-filter></service>

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;import com.game.base.sdk.BaseSDK;
import com.game.base.sdk.Events;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.google.gson.Gson;import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;import java.util.Locale;
import java.util.Map;
import java.util.jar.JarException;
import java.lang.Boolean;import game.billion.block.blast.bbb.MainActivity;
import game.billion.block.blast.bbb.R;
import kotlin.Pair;public class BillionFirebaseMessagingService extends FirebaseMessagingService {private String channelID = "game.puzzle.block.billion.pro.notification";private String channelName = "messageName";int notifyID = 101010;//监控令牌的生成@Overridepublic void onNewToken(@NonNull String token) {super.onNewToken(token);Log.d("BillionFirebaseMessagingService", "onNewToken:"+token);}//监控推送的消息@Overridepublic void onMessageReceived(@NonNull RemoteMessage mge) {super.onMessageReceived(mge);Log.d("BillionFirebaseMessagingService", "From:"+mge.getFrom());Log.d("BillionFirebaseMessagingService", "data:"+mge.getData());Map<String,String> dt = mge.getData();String ti =dt.get("title");           //标题(多语言),JSON字符串try {if (ti != null && !ti.isEmpty()){JSONObject json =new JSONObject(ti);String language = Locale.getDefault().getLanguage();if (language=="pt"){//获取巴西语String resTitle = json.getString("pt");if (resTitle != null && !resTitle.isEmpty()){//显示通知addNotification(resTitle);}}else {String resTitle = json.getString("en");if (resTitle != null && !resTitle.isEmpty()){//显示通知addNotification(resTitle);}}}} catch (JSONException e) {}String mgeId = mge.getMessageId();String intent =dt.get("intent");String strId =dt.get("sid");Pair<String, String>[] params = new Pair[3];params[0] = new Pair<>("message_id", mgeId);params[1] = new Pair<>("type", intent);params[2] = new Pair<>("sid", strId);Events.push("100410", params);}//添加提示private  void addNotification(String resTitle ){if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);NotificationChannel nc=newNotificationChannel(channelID, channelName);if (nc!=null){if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {managerCompat.createNotificationChannel(nc);}}Intent nfIntent = new Intent(this, MainActivity.class);PendingIntent pendingIntent ;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {pendingIntent=PendingIntent.getActivity(this, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE);} else {pendingIntent=PendingIntent.getActivity(this, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);}NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelID);builder.setContentIntent(pendingIntent); // 设置PendingIntentbuilder.setSmallIcon(R.drawable.notification); // 设置状态栏内的小图标builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);builder.setStyle(new NotificationCompat.BigTextStyle());builder.setContentTitle(getString(R.string.app_name));builder.setContentText(resTitle);builder.setWhen(System.currentTimeMillis());builder.setAutoCancel(true);managerCompat.notify(notifyID, builder.build());}}private NotificationChannel newNotificationChannel(String cId, String cName){if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {NotificationChannel channel =new  NotificationChannel(cId, channelName, NotificationManager.IMPORTANCE_HIGH);channel.setSound(null, null);channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);return channel;}return null;}
}

4、测试(google-services.json 记得放应用级中)

a、获取tokn

 //在firebase中检查google版本是否有问题GoogleApiAvailability.getInstance().makeGooglePlayServicesAvailable(this).addOnCompleteListener(new OnCompleteListener<Void>() {@Overridepublic void onComplete(@NonNull Task<Void> task) {if (task.isSuccessful()) {Log.d("Firebase", "onComplete: Play services OKAY");//firebase 推送 (FCM)获取token(FCM令牌)FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {@Overridepublic void onComplete(@NonNull Task<String> task) {if (!task.isSuccessful()){Log.w("Firebase", "Fetching FCM registration token failed", task.getException());return;}// Get new FCM registration tokenString ss= task.getResult();Log.d("Firebase", "onComplete:token getResult "+ss);}});} else {// Show the user some UI explaining that the needed version// of Play services Could not be installed and the app can't run.}}});

b、用tokn就能对固定手机发送消息

相关文章:

Android Firebase (FCM)推送接入

官方文档&#xff1a; 向后台应用发送测试消息 | Firebase Cloud Messaging 1、根级&#xff08;项目级&#xff09;Gradlegradle的dependencies中添加&#xff1a; dependencies {...// Add the dependency for the Google services Gradle pluginclasspath com.google.gm…...

Neo4j恢复

主要记录windows环境下从备份文件中恢复Neo4j&#xff0c; Linux环境同理 备份在上一篇中有介绍&#xff0c;参考: Neo4j备份-CSDN博客 误删数据 为了模拟误删除场景&#xff0c;我们查询Person&#xff0c;并模拟误操作将其进行删除&#xff1b; match(p:Person) return …...

ZZULIOJ 1114: 逆序

题目描述 输入n&#xff08;1<n<10&#xff09;和n个整数&#xff0c;逆序输出这n个整数。 输入 输入n&#xff08;1<n<10&#xff09;&#xff0c;然后输入n个整数。 输出 逆序输出这n个整数&#xff0c;每个整数占4列&#xff0c;右对齐。 样例输入 Copy …...

Linux前后端项目部署

目录 1.jdk&tomcat安装 配置并且测试jdk安装 修改tomcat 配置文件 登入tomcat 发布 安装mysql 导入sql数据 发布项目war包 redis安装 nginx安装 配置nginx域名映射 部署前端项目 centos 7的服务安装 安装jdk 安装tomcat 安装Mysql 安装redis 安装nginx 前后…...

GPT-4与DALL·E 3:跨界融合,开启绘画与文本的新纪元

在人工智能的发展浪潮中&#xff0c;MidTool&#xff08;https://www.aimidtool.com/&#xff09;的GPT-4与DALLE 3的集成代表了一个跨越式的进步。这一集成不仅仅是技术的结合&#xff0c;更是艺术与文字的完美融合&#xff0c;它为创意产业带来了革命性的变革。本文将探讨GPT…...

聊聊PowerJob的Alarmable

序 本文主要研究一下PowerJob的Alarmable Alarmable tech/powerjob/server/extension/Alarmable.java public interface Alarmable {void onFailed(Alarm alarm, List<UserInfoDO> targetUserList); }Alarmable接口定义了onFailed方法&#xff0c;其入参为alarm及tar…...

系列三十五、获取Excel中的总记录数

一、获取Excel中的总记录数 1.1、概述 使用EasyExcel开发进行文件上传时&#xff0c;通常会碰到一个问题&#xff0c;那就是Excel中的记录数太多&#xff0c;使用传统的方案进行文件上传&#xff0c;很容易就超时了&#xff0c;这时可以通过对用户上传的Excel中的数量进行限制…...

VMware workstation安装debian-12.1.0虚拟机并配置网络

VMware workstation安装debian-12.1.0虚拟机并配置网络 Debian 是一个完全自由的操作系统&#xff01;Debian 有一个由普罗大众组成的社区&#xff01;该文档适用于在VMware workstation平台安装debian-12.1.0虚拟机。 1.安装准备 1.1安装平台 Windows 11 1.2软件信息 软…...

centos下系统全局检测工具dstat使用

目录 一&#xff1a;没有需要安装 二&#xff1a;dstat命令参数 三、监测界面各参数含义&#xff08;部分&#xff09; 四、dstat的高级用法 一&#xff1a;没有需要安装 yum install dstat 二&#xff1a;dstat命令参数 有默认选项&#xff0c;执行dstat命令不加任何参数…...

无人机群ros通信

单架无人机与地面站通信 在一个局域网内获取无人机的机载电脑ip 通过地面站ssh到机载电脑&#xff0c;实现通信 多架无人机与地面站通信 在ROS基础上&#xff0c;配置主机和从机&#xff0c;实现主机和从机的话题联通 配置hosts 在主机和从机的/etc/hosts文件中&#xff0c…...

LeetCode刷题:142. 环形链表 II

题目&#xff1a; 是否独立解决&#xff1a;否&#xff0c;参考了解题思路解决问题&#xff0c;思考了用快慢指针&#xff0c;栈&#xff0c;统计链表数量定位尾巴节点&#xff08;因为是环形链表所以是死循环&#xff0c;链表数量用while循环统计不出来&#xff09;都没解决 解…...

Laravel 使用rdkafka_laravel详细教程(实操避坑)

一、选择rdkafka 首先要看版本兼容问题&#xff0c;我的是Laravel5.6&#xff0c;PHP是7.3.13&#xff0c;所以需要下载兼容此的rdkafka&#xff0c;去 Packagist 搜索 kafka &#xff0c;我用的是 enqueue/rdkafka选择里面0.10.5版本&#xff0c; 二、安装rdkafka 在 Larav…...

439 - Knight Moves (UVA)

题目链接如下&#xff1a; Online Judge UVA439 骑士的移动 - 锦依卫议事堂 - 洛谷博客 这里有好几个特别厉害的解法...先存着慢慢看。 我的代码如下&#xff1a; #include <iostream> #include <deque> #include <string> // #define debugstruct node{…...

数据结构(c)冒泡排序

本文除了最下面的代码是我写的&#xff0c;其余是网上抄写的。 冒泡排序 什么是冒泡排序&#xff1f; 冒泡排序&#xff08;Bubble Sort&#xff09;是一种简单的排序算法。它重复地走访过要排序的数列&#xff0c;一次比较两个元素&#xff0c;如果他们的顺序错误就把他们交…...

并发编程之并发容器

目录 并发容器 CopyOnWriteArrayList 应用场景 常用方法 读多写少场景使用CopyOnWriteArrayList举例 CopyOnWriteArrayList原理 CopyOnWriteArrayList 的缺陷 扩展迭代器fail-fast与fail-safe机制 ConcurrentHashMap 应用场景 常用方法 并发场景下线程安全举例 Con…...

K8s---存储卷(动态pv和pvc)

当我要发布pvc可以生成pv&#xff0c;还可以共享服务器上直接生成挂载目录。pvc直接绑定pv。 动态pv需要两个组件 1、卷插件&#xff1a;k8s本生支持的动态pv创建不包括nfs&#xff0c;需要声明和安装一个外部插件 Provisioner: 存储分配器。动态创建pv,然后根据pvc的请求自动…...

JS判断对象是否为空对象的几种方法

通过JSON自带的stringify()方法判断 function isEmptyObj(obj) {return JSON.stringify(obj) {} } console.log(对象是否为空&#xff1a;, isEmptyObj({}))for in 循环判断 function isEmptyObj(obj) {for(let item in obj) {return true}return false } console.log(对…...

算法通关村第十五关—用4KB内存寻找重复元素(青铜)

用4KB内存寻找重复元素 用4KB内存寻找重复元素 题目要求&#xff1a;给定一个数组&#xff0c;包含从1到N的整数&#xff0c;N最大为32000&#xff0c;数组可能还有重复值&#xff0c;且N的取值不定&#xff0c;若只有4KB的内存可用&#xff0c;该如何打印数组中所有重复元素。…...

【PHP】判断字符串是否是有效的base64编码

目录 1.检测长度&#xff1a; 2.检查字符集&#xff1a; 3.判断是否能正常解码 在PHP中&#xff0c;判断一个字符串是否是有效的Base64编码&#xff0c;可以通过以下几种方法&#xff1a; 1.检测长度&#xff1a; Base64编码的字符串长度必须是4的倍数&#xff08;对于标准…...

鼎盛合|测量精度SOC芯片开发中的技术问题整理

SOC芯片近几年的发展势头迅猛&#xff0c;许多行业中俱可见其身影。SOC芯片并不是传统意义上的芯片&#xff0c;它是一个由多种功能集成的一个芯片。SOC芯片自身在出厂时便带有部分程序&#xff0c;是为了方便设计开发而针对某些行业设计的特定功能。如芯海的SOC芯片大多数则是…...

在HarmonyOS ArkTS ArkUI-X 5.0及以上版本中,手势开发全攻略:

在 HarmonyOS 应用开发中&#xff0c;手势交互是连接用户与设备的核心纽带。ArkTS 框架提供了丰富的手势处理能力&#xff0c;既支持点击、长按、拖拽等基础单一手势的精细控制&#xff0c;也能通过多种绑定策略解决父子组件的手势竞争问题。本文将结合官方开发文档&#xff0c…...

遍历 Map 类型集合的方法汇总

1 方法一 先用方法 keySet() 获取集合中的所有键。再通过 gey(key) 方法用对应键获取值 import java.util.HashMap; import java.util.Set;public class Test {public static void main(String[] args) {HashMap hashMap new HashMap();hashMap.put("语文",99);has…...

LeetCode - 394. 字符串解码

题目 394. 字符串解码 - 力扣&#xff08;LeetCode&#xff09; 思路 使用两个栈&#xff1a;一个存储重复次数&#xff0c;一个存储字符串 遍历输入字符串&#xff1a; 数字处理&#xff1a;遇到数字时&#xff0c;累积计算重复次数左括号处理&#xff1a;保存当前状态&a…...

Java - Mysql数据类型对应

Mysql数据类型java数据类型备注整型INT/INTEGERint / java.lang.Integer–BIGINTlong/java.lang.Long–––浮点型FLOATfloat/java.lang.FloatDOUBLEdouble/java.lang.Double–DECIMAL/NUMERICjava.math.BigDecimal字符串型CHARjava.lang.String固定长度字符串VARCHARjava.lang…...

使用van-uploader 的UI组件,结合vue2如何实现图片上传组件的封装

以下是基于 vant-ui&#xff08;适配 Vue2 版本 &#xff09;实现截图中照片上传预览、删除功能&#xff0c;并封装成可复用组件的完整代码&#xff0c;包含样式和逻辑实现&#xff0c;可直接在 Vue2 项目中使用&#xff1a; 1. 封装的图片上传组件 ImageUploader.vue <te…...

如何为服务器生成TLS证书

TLS&#xff08;Transport Layer Security&#xff09;证书是确保网络通信安全的重要手段&#xff0c;它通过加密技术保护传输的数据不被窃听和篡改。在服务器上配置TLS证书&#xff0c;可以使用户通过HTTPS协议安全地访问您的网站。本文将详细介绍如何在服务器上生成一个TLS证…...

Redis数据倾斜问题解决

Redis 数据倾斜问题解析与解决方案 什么是 Redis 数据倾斜 Redis 数据倾斜指的是在 Redis 集群中&#xff0c;部分节点存储的数据量或访问量远高于其他节点&#xff0c;导致这些节点负载过高&#xff0c;影响整体性能。 数据倾斜的主要表现 部分节点内存使用率远高于其他节…...

初探Service服务发现机制

1.Service简介 Service是将运行在一组Pod上的应用程序发布为网络服务的抽象方法。 主要功能&#xff1a;服务发现和负载均衡。 Service类型的包括ClusterIP类型、NodePort类型、LoadBalancer类型、ExternalName类型 2.Endpoints简介 Endpoints是一种Kubernetes资源&#xf…...

springboot整合VUE之在线教育管理系统简介

可以学习到的技能 学会常用技术栈的使用 独立开发项目 学会前端的开发流程 学会后端的开发流程 学会数据库的设计 学会前后端接口调用方式 学会多模块之间的关联 学会数据的处理 适用人群 在校学生&#xff0c;小白用户&#xff0c;想学习知识的 有点基础&#xff0c;想要通过项…...

AirSim/Cosys-AirSim 游戏开发(四)外部固定位置监控相机

这个博客介绍了如何通过 settings.json 文件添加一个无人机外的 固定位置监控相机&#xff0c;因为在使用过程中发现 Airsim 对外部监控相机的描述模糊&#xff0c;而 Cosys-Airsim 在官方文档中没有提供外部监控相机设置&#xff0c;最后在源码示例中找到了&#xff0c;所以感…...