在当今的移动应用开发领域,消息推送功能已经成为提高用户粘性和应用价值的重要手段。而Firebase Cloud Messaging(FCM)作为Google提供的跨平台消息推送服务,因其简单易用、功能强大而受到广大开发者的青睐。本文将带你一步步学会如何使用FCM实现手机App的跨平台消息推送。
第一步:准备工作
在开始之前,你需要准备以下材料:
- Firebase项目:在Firebase控制台创建一个新的项目。
- Android Studio:下载并安装最新版本的Android Studio。
- iOS开发环境:如果你要支持iOS平台,需要安装Xcode。
- Android和iOS设备或模拟器:用于测试你的应用。
第二步:集成FCM到你的应用
对于Android应用:
添加依赖:在你的
build.gradle文件中添加以下依赖:implementation 'com.google.firebase:firebase-messaging:22.0.0'初始化FCM:在你的
Application类中初始化FCM:FirebaseApp.initializeApp(this);注册设备token:在你的应用中注册设备token,以便FCM可以识别你的设备:
FirebaseMessaging.getInstance().getToken() .addOnCompleteListener(task -> { if (!task.isSuccessful()) { Log.w("FCM", "Fetching FCM registration token failed", task.getException()); return; } // Get new FCM registration token String token = task.getResult(); // TODO: Send token to your server or save it to local storage });
对于iOS应用:
添加依赖:在你的
Podfile文件中添加以下依赖:pod 'Firebase/Messaging'初始化FCM:在你的
AppDelegate类中初始化FCM:FirebaseApp.configure()注册设备token:在你的应用中注册设备token:
Messaging.messaging().requestPermission { status, error in if let error = error { print("Error: \(error)") } else { if status == .authorized { Messaging.messaging().token { token, error in if let error = error { print("Error: \(error)") } else if let token = token { print("FCM registration token: \(token)") } } } } }
第三步:发送消息
向单个设备发送消息:
String registrationToken = "YOUR_REGISTRATION_TOKEN";
String messageBody = "Hello, world!";
String title = "FCM Message";
String notificationBody = "This is a notification body";
String notificationJson = "{ \"notification\": { \"title\": \"" + title + "\", \"body\": \"" + notificationBody + "\" } }";
FCMMessage message = new FCMMessage.builder()
.setData(new HashMap<String, String>())
.setNotification(new FCMNotification()
.setTitle(title)
.setBody(notificationBody))
.build();
Messaging.sendToRegistrationToken(registrationToken, message)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.d("FCM", "Message sent successfully");
} else {
Log.e("FCM", "Failed to send message", task.getException());
}
});
let registrationToken = "YOUR_REGISTRATION_TOKEN"
let messageBody = "Hello, world!"
let title = "FCM Message"
let notificationBody = "This is a notification body"
let notificationJson = "{\"notification\":{\"title\":\"\(title)\",\"body\":\"\(notificationBody)\"}}"
let message = FCMMessage(data: ["message": messageBody], notification: FCMNotification(title: title, body: notificationBody))
FCMMessaging.messaging().send(message, to: registrationToken) { error, response in
if let error = error {
print("Error: \(error)")
} else {
print("Message sent successfully")
}
}
向一组设备发送消息:
String[] registrationTokens = {"TOKEN_1", "TOKEN_2", "TOKEN_3"};
String messageBody = "Hello, world!";
String title = "FCM Message";
String notificationBody = "This is a notification body";
String notificationJson = "{ \"notification\": { \"title\": \"" + title + "\", \"body\": \"" + notificationBody + "\" } }";
FCMMessage message = new FCMMessage.builder()
.setData(new HashMap<String, String>())
.setNotification(new FCMNotification()
.setTitle(title)
.setBody(notificationBody))
.build();
MulticastMessage multicastMessage = new MulticastMessage()
.setNotification(new FCMNotification()
.setTitle(title)
.setBody(notificationBody))
.addAllTo("tokens", registrationTokens);
Messaging.send(multicastMessage)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.d("FCM", "Message sent successfully");
} else {
Log.e("FCM", "Failed to send message", task.getException());
}
});
let registrationTokens = ["TOKEN_1", "TOKEN_2", "TOKEN_3"]
let messageBody = "Hello, world!"
let title = "FCM Message"
let notificationBody = "This is a notification body"
let notificationJson = "{\"notification\":{\"title\":\"\(title)\",\"body\":\"\(notificationBody)\"}}"
let message = FCMMessage(data: ["message": messageBody], notification: FCMNotification(title: title, body: notificationBody))
let multicastMessage = MulticastMessage(notification: FCMNotification(title: title, body: notificationBody), tokens: registrationTokens)
FCMMessaging.messaging().send(multicastMessage) { error, response in
if let error = error {
print("Error: \(error)")
} else {
print("Message sent successfully")
}
}
向所有设备发送消息:
String messageBody = "Hello, world!";
String title = "FCM Message";
String notificationBody = "This is a notification body";
String notificationJson = "{ \"notification\": { \"title\": \"" + title + "\", \"body\": \"" + notificationBody + "\" } }";
FCMMessage message = new FCMMessage.builder()
.setData(new HashMap<String, String>())
.setNotification(new FCMNotification()
.setTitle(title)
.setBody(notificationBody))
.build();
TopicMessage topicMessage = new TopicMessage()
.setNotification(new FCMNotification()
.setTitle(title)
.setBody(notificationBody))
.setTopic("YOUR_TOPIC");
Messaging.sendToTopic("YOUR_TOPIC", message)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.d("FCM", "Message sent successfully");
} else {
Log.e("FCM", "Failed to send message", task.getException());
}
});
let messageBody = "Hello, world!"
let title = "FCM Message"
let notificationBody = "This is a notification body"
let notificationJson = "{\"notification\":{\"title\":\"\(title)\",\"body\":\"\(notificationBody)\"}}"
let message = FCMMessage(data: ["message": messageBody], notification: FCMNotification(title: title, body: notificationBody))
let topicMessage = TopicMessage(notification: FCMNotification(title: title, body: notificationBody), topic: "YOUR_TOPIC")
FCMMessaging.messaging().send(topicMessage) { error, response in
if let error = error {
print("Error: \(error)")
} else {
print("Message sent successfully")
}
}
第四步:接收和处理消息
在应用中接收和处理消息,需要注册一个FirebaseMessagingService或UNUserNotificationCenterDelegate。
对于Android应用:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage message) {
// Handle message received
}
@Override
public void onNewToken(String token) {
// Handle new token received
}
}
对于iOS应用:
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Register for notifications
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { _, _ in }
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// Handle notification response
completionHandler()
}
}
总结
使用FCM实现手机App的跨平台消息推送非常简单,只需按照以上步骤进行操作即可。希望本文能帮助你轻松学会使用FCM,让你的应用更具竞争力。