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需要的插件和依赖
- 在工程级别(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' } // 必填项
}
}
- 在项目级别(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相关的服务
- 创建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());
}
}
}
-
创建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服务器
-
注册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" />
-
需要注意的问题
-
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()获得,设置进去即可