使用 FCM 发送推送通知
Google 弃用了 Google Cloud Messaging (GCM) 并推出了新的推送通知服务器,即 Firebase Cloud Messaging (FCM)。 FCM 和 GCM 一样,FCM 也是移动平台的跨平台消息解决方案
Firebase Cloud Messaging 可以发送三种类型的消息 (Message types)
1.通知消息
2.数据消息
3.包含通知和数据的消息
Firebase 云消息传递集成步骤:-
1.在 Firbase 控制台中设置新项目或导入项目(https://firebase.google.com/)
2.在Firebase App中添加同名的App。
3.获取“google-services.json”文件并将该文件放入您项目的应用文件夹中。该文件包含Google服务的所有Url和Keys,因此请勿更改或编辑此文件。
4.在 Project for Firebase 中添加新的 Gradle 依赖项。
//app/build.gradle
dependencies {
compile 'com.google.firebase:firebase-messaging:9.6.0'
}
apply plugin: 'com.google.gms.google-services'
5.创建一个类,其中包含我们在整个应用中为 FCM 使用的所有常量值。
public class Config {
public static final String TOPIC_GLOBAL = "global";
// broadcast receiver intent filters
public static final String REGISTRATION_COMPLETE = "registrationComplete";
public static final String PUSH_NOTIFICATION = "pushNotification";
// id to handle the notification in the notification tray
public static final int NOTIFICATION_ID = 100;
public static final int NOTIFICATION_ID_BIG_IMAGE = 101;
public static final String SHARED_PREF = "ah_firebase";
}
6。创建一个名为 MyFirebaseInstanceIDService.java 的类,它将接收每个应用程序唯一的 firebase 注册 ID。注册 id 用于向单个设备发送消息。
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// Saving reg id to shared preferences
storeRegIdInPref(refreshedToken);
// sending reg id to your server
sendRegistrationToServer(refreshedToken);
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
registrationComplete.putExtra("token", refreshedToken);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
private void sendRegistrationToServer(final String token) {
// sending gcm token to server
Log.e(TAG, "sendRegistrationToServer: " + token);
}
private void storeRegIdInPref(String token) {
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("regId", token);
editor.commit();
}
}
7.再创建一个名为 MyFirebaseMessagingService.java 的服务类。这将接收 Firebase 消息。
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
private NotificationUtils notificationUtils;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
handleNotification(remoteMessage.getNotification().getBody());
}
}
private void handleNotification(String message) {
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
}else{
// If the app is in background, firebase itself handles the notification
}
}
/**
* Showing notification with text only
*/
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}
/**
* Showing notification with text and image
*/
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}
}
8.在AndroidManifest.xml中添加这两个firebase服务MyFirebaseMessagingService和MyFirebaseInstanceIDService。
<!-- Firebase Notifications -->
<service android:name=".service.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".service.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<!-- ./Firebase Notifications -->
现在只需Send your First Message
注意事项:
*1.阅读谷歌文档Firebase Cloud Messaging *
2.如果您想将适用于 Android 的 GCM 客户端应用迁移到 Firebase Cloud Messaging,请按照以下步骤和文档 (Migrate a GCM Client
App)
3.Android 示例教程和代码 (Receive Reengagement Notifications)