【发布时间】:2018-12-09 13:59:39
【问题描述】:
尝试使用 android 中的改造库发送 fcm 通知。我想向其他 android 设备显示带有标题和消息的通知。 这是用于推送通知的代码和示例文件。
使用改造调用发送推送通知的功能:
private void sendNotification(String deviceId,String sender,String message)
{
FirebaseApi apiService =
FirebaseClient.getClient().create(FirebaseApi.class);
NotifyData notifydata = new NotifyData(sender,message);
Call<FirebaseMessage> call = apiService.sendMessage(new
FirebaseMessage(deviceId, notifydata));
call.enqueue(new Callback<FirebaseMessage>() {
@Override
public void onResponse(Call<FirebaseMessage> call,
Response<FirebaseMessage> response) {
Log.e("Message Response","Send");
}
@Override
public void onFailure(Call<FirebaseMessage> call, Throwable t) {
Log.e("Message Response","Fail");
}
});
}
FirebaseMessage 类:
public class FirebaseMessage {
String to;
NotifyData notification;
public FirebaseMessage(String to, NotifyData notification) {
this.to = to;
this.notification = notification;
}
}
NotifyData 类:
public class NotifyData {
String title;
String body;
public NotifyData(String title, String body ) {
this.title = title;
this.body = body;
}
}
FirebaseClient 类:
public class FirebaseClient {
public static Retrofit RETROFIT = null;
public static Retrofit getClient(){
if(RETROFIT==null){
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
RETROFIT = new Retrofit.Builder()
.baseUrl(StaticConfig.FIREBASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return RETROFIT;
}
}
FirebaseApi 类:
public interface FirebaseApi {
@Headers({"Authorization: key=Legacy Service Key",
"Content-Type:application/json"})
@POST("fcm/send")
Call<FirebaseMessage> sendMessage(@Body FirebaseMessage message);
}
在 MyFirebaseMessagingService 类中:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String title=remoteMessage.getData().get("title");
String body=remoteMessage.getData().get("body");
sendNotification(title, body);
}
但它每次都显示空白通知,标题为空,正文为空。 如何正确通过 remoteMessage 检索我的 notifydata。
【问题讨论】:
-
使用 FCM 发送消息需要您指定所谓的服务器密钥。顾名思义,此密钥应仅在您控制的环境中使用,这通常意味着它不应在 Android 设备上使用。在您的 Android 应用程序中包含此密钥意味着恶意用户可能(因此将)找到它,并可以使用它代表您向您的所有用户发送消息。要使用 FCM 安全地发送消息,您应该始终从受信任的环境(例如您控制的服务器或 Cloud Functions)发送它们。
-
Frank van Puffelen 你能给我一些示例代码如何实现 fcm 发送消息吗?
-
有关示例,请参阅firebase.google.com/docs/functions/…。
-
谢谢.. 我会处理的。
标签: android firebase push-notification firebase-cloud-messaging retrofit