安卓项目开发,使用谷歌Firebase FCM实现消息推送

不废话,直接上正文!

谷歌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功能已经添加完成了,一些非必选设置可以参考官网。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值