不废话,直接上正文!

谷歌FCM文档地址:https://firebase.google.com/docs/cloud-messaging/android/client?authuser=0

照着文档来还是比较顺利的

注意:我在项目中使用的是androidx,建议使用androidx,会避免一些BUG

一、先在项目中添加Firebase核心库

文档地址:https://firebase.google.com/docs/android/setup?authuser=0

1、登录Firebase控制台,添加项目,得到 google-services.json文件,放到项目的app目录下。

2、在项目级build.gradle添加:

buildscript {

  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
  }

  dependencies {
    // ...

    // Add the following line:
    classpath 'com.google.gms:google-services:4.2.0'  // Google Services plugin
  }
}

allprojects {
  // ...

  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
    // ...
  }
}

 3、在应用级build.gradle添加:

apply plugin: 'com.android.application'

android {
  // ...
}

// Add the following line to the bottom of the file:
apply plugin: 'com.google.gms.google-services'  // Google Play services Gradle plugin

注意:apply plugin: 'com.google.gms.google-services' 一定添加在最后

4、dependencies中添加Firebase核心库:

implementation 'com.google.firebase:firebase-core:17.0.0'

至此Firebase就成功添加到项目里了。

二、添加FCM推送功能

1、dependencies中添加:

implementation 'com.google.firebase:firebase-messaging:20.0.0'

2、AndroidManifest内添加:

引用谷歌的介绍:一项继承 FirebaseMessagingService 的服务。除接收应用通知外,如果您还希望在后台进行更多的消息处理工作,则必须添加此服务。要接收前台应用中的通知、接收数据有效负载以及发送上行消息等,您必须扩展此服务。

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

谷歌Demo内的MyFirebaseMessagingService:

https://github.com/firebase/quickstart-android/blob/d854bf66ff07abe08f371a07d261508df7df49fb/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/java/MyFirebaseMessagingService.java#L106-L120

至此FCM功能已经添加完成了,一些非必选设置可以参考官网。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐