在Android项目中使用FCM(FirebaseCloudMessage)

FCM简介

1. FCM是Google的GCM升级版的一种消息推送框架(官方网站)
2. FCM可以在官方网站的控制台Firebase console上发送通知,但是GCM不能(需要在官方网站添加上你的应用才可以登陆到控制台)

FCM使用前提

  • 设备必须是android4.0以上,Google Play Services 必须是 11.2.0以上版本
  • Android SDK Manager 必须有Google Play services SDK
  • Android Studio必须是1.5以上版本

FCM接入

官方接入文档

  • 下载google-services.json文件,并将文件放置在app目录下
说明:如果要在不同buildType或者productFlavors下区分不同的json文件,请建立对应的文件夹,并将json文件copy至对应文件夹的根目录下
 不同的buildType时 
 // dogfood and release are build types.
app/
google-services.json
src/dogfood/google-services.json
src/release/google-services.json
...

不同的productFlavors时
// free and paid are product flavors.
app/
google-services.json
src/dogfood/paid/google-services.json
src/release/free/google-services.json
...
  • 加入FCM需要的插件和依赖
  1. 在工程级别(Project-level)的build.gradle中加入:
buildscript {    
    repositories {
        jcenter()
        google() // 必填项(gradle plugin 3.x以上) 
        或者
        maven { url 'https://maven.google.com' } // 必填项
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0' // gradle pulagin 版本
        classpath 'com.google.gms:google-services:3.1.0' // service 插件的版本(最新参考官网)
    }
}

allprojects {
    repositories {
        jcenter()
        google() // 必填项(gradle plugin 3.x以上) 
        或者
        maven { url 'https://maven.google.com' } // 必填项
    }
}
  1. 在项目级别(Model-level)的build-gradle中加入:
apply plugin: 'com.android.application'

android {
      ...
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    ...
    implementation 'com.google.firebase:firebase-messaging:12.0.1' // FCM推送使用的依赖
}

apply plugin: 'com.google.gms.google-services' 
// 必须要放在最后,不然会报错:Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to X.X.X.

如果引用了Google其他服务,比如google地图,那么需要版本一致

//下方的firebase-messaging 和 play-services-maps 和 play-services版本号必须一致
    compile 'com.google.firebase:firebase-messaging:11.2.0'
    compile 'com.google.android.gms:play-services-maps:11.2.0'
    compile 'com.google.android.gms:play-services:11.2.0'
    compile 'com.google.gms:google-services:3.1.0'
  • 添加FCM相关的服务
  1. 创建FCMMessagingService,继承FirebaseMessagingService
public class FCMMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        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"));
        }
    }

    @Override
    public void onDeletedMessages() {
        super.onDeletedMessages();
    }

    @Override
    public void onMessageSent(String s) {
        super.onMessageSent(s);
    }

    @Override
    public void onSendError(String s, Exception e) {
        super.onSendError(s, e);
    }

    private void sendNotification(Context iContext, String messageTitle, String messageBody) {

        NotificationManager notificationManager = (NotificationManager) iContext.getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, MessageActivity.class); // 接收到通知后,点击通知,启动 MessageActivity

        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        long[] pattern = {500,500,500,500,500};
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(),"-1")
                .setTicker(messageTitle)
                .setSmallIcon(R.drawable.ic_stat_notify)
                .setContentTitle("push 通知 标题")
                .setAutoCancel(true)
                .setContentText(messageBody)
                .setWhen(System.currentTimeMillis())
                .setVibrate(pattern)
                .setLights(Color.BLUE, 1, 1)
        builder.setDefaults(NotificationCompat.DEFAULT_SOUND | NotificationCompat.DEFAULT_VIBRATE);

        builder.setContentIntent(pendingIntent);
//        builder.setFullScreenIntent(pendingIntent, true);//将一个Notification变成悬挂式Notification

        if (notificationManager != null) {
            notificationManager.notify(0, builder.build());
        }
    }
}
  1. 创建FCMInstanceIDService,继承FirebaseInstanceIdService,参考官网
唯一Token的获取和上传

最初启动您的应用时,FCM SDK 会为客户端应用实例生成一个注册令牌。如果您希望定位单台设备或创建设备组,则需要通过继承 FirebaseInstanceIdService
来访问此令牌。
当您需要检索当前令牌时,请调用 FirebaseInstanceId.getInstance().getToken()
如果令牌尚未生成,此方法将返回 null。

public class FCMInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.v("FCM----", refreshedToken);
        sendRefreshToken(refreshedToken);
    }

    public void sendRefreshTokenToService(String refreshedToken){
        //这里是往自己app应用的后台发送刷新refreshedToken的api
    }
}

Firebase建议我们复写onTokenRefresh方法并且及时上传更新的Token通知App服务器

  1. 注册Service
        <service android:name=".FCMInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

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

        <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
     See README(https://goo.gl/l4GJaQ) for more. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/ic_stat_notify" />
        <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
             notification message. See README(https://goo.gl/6BKBk7) for more. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />

  • 需要注意的问题
  1. FCM有两种消息

1.1 显示消息:仅当应用处于前台时,消息才会触发 onMessageReceived() 回调
1.2 数据消息:程序后台运行时接收到通知,不会走FirebaseMessagingService的 onMessageReceived() 方法,而是显示在系统托盘中,此时点击通知,会打开App中的默认启动Activity,并将数据放在Intent的extras中传送。

所以如果app处于后台或者被killed,想要点击通知显示MessageActivity,可以这样做:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (getIntent().getExtras() != null) {
            for (String s : getIntent().getExtras().keySet()) {
                Log.d("MainActivity", s + "--" + getIntent().getExtras().get(s)); 
            // 在官网的发送notification 使用高级选项可以自定义 键值对,最终会在getIntent().getExtras()中获取到
            }
            Intent intent = new Intent(this, MessageActivity.class);
            startActivity(intent);
        }
    }
}

使用FCM云消息推送

目标分为三种:

  • 用户细分--->对所有安装过程序的client端进行发送推送
  • 主 题--->官方链接
  • 单个设备--->对指定的Client进行发送,需要一个FCM注册令牌,程序运行起来时,通过FirebaseInstanceId.getInstance().getToken()获得,设置进去即可
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,058评论 25 707
  • FCM,即Firebase Cloud Messaging Firebase,Firebase是一家实时后端数据库...
    阿敏其人阅读 34,034评论 4 15
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • 六丰商城提示:减了一年的肥过年的几天全给增回来了有木有?每天的大鱼大肉让自己的身体多少有些吃不消,这个时候...
    nongyedianshang阅读 307评论 0 0
  • 今年的6月份,有之前一段时间的积累。积累指的是(阅读了几本影响思维模式的书)几乎颠覆了之前我对事物认知的很多观点,...
    定见阅读 92评论 0 0