❤️Android FCM 消息(Google推送) ❤️

3,489 阅读3分钟

小知识,大挑战!本文正在参与「程序员必备小知识」创作活动

本文已参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金。

🔥 介绍

Firebase 云消息传递 (FCM) 提供了广泛的消息传递选项和功能,是一种跨平台消息传递解决方案,

💥 消息类型

使用 FCM,您可以向客户端发送两种类型的消息:

  • 通知消息,有时被认为是"显示消息"。这些由 FCM SDK 自动处理。
  • 数据消息,由客户端应用程序处理。

通知消息可以包含可选的数据负载。两种消息类型的最大负载均为 4000 字节,但从 Firebase 控制台发送消息强制执行 1024 个字符限制。

💥 消息接收

使用港版三星S8做的测试。

  • 前台运行:可收到消息,但是不弹通知栏,如果想弹消息可根据收到的内容自行处理。

  • 后台运行:可收到消息,如不拦截消息,会直接弹通知栏。

  • 杀死程序:收不到消息。

如果是国内阉割后的谷歌服务,不管哪种状态可能都收不到推送。

🔥 前置条件

FCM 运行环境要求:

  • Android 4.1 或更高版本;
  • 安装了 Google Play Store 应用程序的设备。

应用程序可以不上传到 Google Play 商店。

💥 SDK接入要求

  • 目标 API 级别 16(Jelly Bean)或更高
  • 使用 Android 4.1 或更高版本
  • 使用 Jetpack (AndroidX),其中包括满足以下版本要求:
    • com.android.tools.build:gradle v3.2.1 或更高版本
    • compileSdkVersion 28 或更高。

💥 创建 Firebase 项目

后续3步一直同意就行。项目就添加好了。

🔥 添加Android应用

💥 注册应用

💥 下载配制文件

看图导入。

💥 添加Firebase SDK

🌀 <项目>/build.gradle

buildscript {
  repositories {
    google()

  }
  dependencies {
    classpath 'com.google.gms:google-services:4.3.10'

  }
}

allprojects {
  ...
  repositories {
    google()
    ...
  }
}

🌀 <项目>/<应用模块>/build.gradle

apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'


dependencies {
  implementation platform('com.google.firebase:firebase-bom:28.4.2')
  implementation 'com.google.firebase:firebase-analytics'
  implementation 'com.google.firebase:firebase-messaging'
}

🌀 Sync now

🔥 添加云消息配制

💥 <项目>/<应用模块>/build.gradle

dependencies {
  //新增
  implementation 'com.google.firebase:firebase-messaging'
}

💥 继承 FirebaseMessagingService

public class FCMMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        MLog.e("onMessageReceived");
        if (remoteMessage.getNotification() != null && remoteMessage.getNotification().getBody() != null) {
            sendNotification(getApplicationContext(), remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        } else {
            sendNotification(getApplicationContext(), remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
        }
    }

    private void sendNotification(Context iContext, String messageTitle, String messageBody) {
        MLog.e("Notification:"+messageTitle+":"+messageBody);
    }

    @Override
    public void onNewToken(@NonNull String token) {
        super.onNewToken(token);
        //将令牌发送到后台服务器。
        MLog.e("onNewToken:"+token);
        //服务端应清楚无用token,否则一台设备会发多条消息。
    }
}

💥 声明 FCMMessagingService

        <service
            android:name=".FCMMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

onNewToken 被调用时有两种情况:

  • 在应用程序初始启动时生成新令牌时
  • 每当现有令牌更改时,更改现有令牌时有三种情况:
    • 应用程序恢复到新设备
    • 用户卸载/重新安装应用
    • 用户清除应用数据

💥 初始化并生成令牌

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        FirebaseApp.initializeApp(this);
        initFirebase();
    }
    private void initFirebase(){
        MLog.e( "initFirebase");
        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(Task<String> task) {
                        if (!task.isSuccessful()) {
                            MLog.e("Fetching FCM FirebaseMessaging token failed:"+task.getException());
                            return;
                        }
                        // Get new FCM registration token
                        String token = task.getResult();
                        MLog.e( "initFirebase:"+token);
                    }
                });
    }
}

💥 运行项目

2021-10-29 15:45:36.316 21005-21005/? E/-SCC-: initFirebase:d8uGdCOrTr6q8X4RQUDW77:APxxxxxxxxxxxxxxlnzBtdtgfOvtJ0cU6cPuQ
2021-10-29 15:45:36.318 21005-21142/? E/-SCC-: onNewToken:d8uGdCOrTr6q8X4RQUDW77:APxxxxxxxxxxxxxxlnzBtdtgfOvtJ0cU6cPuQ

🔥 云消息传递

iOS需要上传证书,Android 则不需要。如下:

🔥 服务端

搞定。

🔥 传送门

注册链接

文档链接

服务端文档传送门