【发布时间】:2017-05-10 20:15:57
【问题描述】:
在 Firebase 控制台中,我看到了使用应用“com.example”(其中 com.example 是应用名称)向用户细分发送通知的选项。
如图所示:
但是如何使用 FCM REST API 从服务器端进行操作:
【问题讨论】:
-
你找到方法了吗?
标签: android firebase firebase-cloud-messaging
在 Firebase 控制台中,我看到了使用应用“com.example”(其中 com.example 是应用名称)向用户细分发送通知的选项。
如图所示:
但是如何使用 FCM REST API 从服务器端进行操作:
【问题讨论】:
标签: android firebase firebase-cloud-messaging
我找到了解决方案 您可以为您的应用订阅特定主题,例如您的 FirebaseInstanceIdService 类中的应用包名称,以便您可以发送数据消息,如
{
"to" : "/topics/your_package_name",
"data" : {
"key1" : "value 1",
"key2": "value 2",
...
}
}
这是在 FirebaseInstanceIdService 类中为您的应用订阅主题的代码
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService
{
private final String TAG="your_tag";
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
FirebaseMessaging.getInstance().subscribeToTopic("your_app_package_name");
}
}
它对我有用
【讨论】:
根据操作系统订阅您的用户
主题:android 用户的“android”
主题:iOS 用户的“iOS”
(或任何你想要的名字)
然后发送到那个主题...
【讨论】:
不幸的是,它是not possible to send messages to User Segments using the FCM REST API。
作为替代方案,您必须使用send messages to multiple devices 的其他方法,例如简单地使用registration_ids 参数和主题消息传递(我认为这对您的用例来说是最可取的)。
这里是有关如何发送此using Postman 或cURL 的示例。
【讨论】:
registration_ids。如果您有超过一千个用户,则必须发出批量请求,每个请求最多有 1000 个注册令牌。
https://iid.googleapis.com/iid/v1/[REGISTRATIONTOKEN]/rel/topics/[TOPIC] 发送 POST(使用您的服务器密钥授权)。
使用以下参数对https://fcm.googleapis.com/fcm/send进行后调用:-
标题:-
Content-Type--application/json
Authorization--key={你的服务器密钥}
正文:-
{
"data": {
"my_custom_key" : "my_custom_value",
"message" : "notification message"
},
"registration_ids": ["device_token1,device_token2,.........."]
}
编辑:-
基本上你需要做的是,每当你需要发送通知时,你必须从你的服务器端调用这个 POST 方法,你的应用程序会自动在 OnMessageReceived 中得到一个调用。你可以这样处理:-
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Map<String, String> data=remoteMessage.getData();
Log.d(TAG, "From: " + data.toString());
String value=data.get("my_custom_key");
Log.d(TAG, "From: " + value);
String msg=data.get("message");
Log.d(TAG, "From: " + msg);
sendNotification(msg,value,remoteMessage.getSentTime());
}
【讨论】:
"registration_ids": ["device_token1,device_token2,.........."]:我想发送给任何安装了该应用程序的用户。请参阅更新的问题。从使用用户段选项的firebase控制台我可以在不需要设备令牌的情况下发送。因为我的通知是通用的
您实际上需要向主题发送消息..所有订阅主题的成员都会收到您的消息..
只需查看链接..
https://developers.google.com/cloud-messaging/topic-messaging
【讨论】: