繁体   English   中英

Firebase 来自 Android 应用程序的云消息通知

[英]Firebase Cloud Messaging Notification From Android App

我想从 android 设备向多个 android 设备发送通知,我正在使用 FCM 发送通知,但问题是我没有收到任何东西。 我在stackoverflow上关注了一些教程和一些链接,但我不明白我做错了什么。 我尝试使用 retrofit 和 okhttp 发送通知,但我似乎无法生成通知。 从 Firebase 控制台我可以生成通知,但不能从 android 应用程序生成通知。

使用 Retrofit

Retrofit代码

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://fcm.googleapis.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
API api = retrofit.create(API.class);
PushNotificationModel pushNotificationModel = new PushNotificationModel(
        "/topics/Receive",
        new NotificationModel(
                "Mobile",
                "I am ready for you"
        )
);
Call<PushNotificationModel> call = api.sendNotification(pushNotificationModel);
call.enqueue(new Callback<PushNotificationModel>() {
    @Override
    public void onResponse(Call<PushNotificationModel> call, Response<PushNotificationModel> response) {
        Log.e(TAG, "onResponse: Code: " + response.code() /*+ " Response: " + new Gson().toJson(response)*/);
    }

    @Override
    public void onFailure(Call<PushNotificationModel> call, Throwable t) {
        Log.e(TAG, "onFailure: " + t.getMessage());
    }
});

POJO 类

public class PushNotificationModel {
    private String to;
    private NotificationModel notification;

    public PushNotificationModel(String to, NotificationModel notification) {
        this.to = to;
        this.notification = notification;
    }
}

public class NotificationModel {
    private String title, body;

    public NotificationModel(String title, String body) {
        this.title = title;
        this.body = body;
    }
}

界面

public interface API {

    @Headers({
            "Authorization:key=AAAAO-53MSs:APA91bFR...JNL7GjX1D",
            "Content-Type:application/json"
    })
    @POST("fcm/send")
    Call<PushNotificationModel> sendNotification(@Body PushNotificationModel pushNotificationModel);
}

解决方案

我能够通过清理和重建项目来解决问题,有时在项目的第一次初始部署中我无法收到通知,因此关闭应用程序,从多任务栏中删除并重新打开应用程序解决了我能够解决的问题正确接收通知:)。 不管你使用什么凌空或 retrofit 都适用。

下面的代码将向订阅了topicName主题的一组设备发送通知。

//send notification to other user
public void sendNotificationToUser() {
        JSONObject mainObj = new JSONObject();
        try {
            mainObj.put("to", "/topics/" + topicName); // topicName = your topic name
            JSONObject notificationObj = new JSONObject();
            notificationObj.put("title", "Add your title");
            notificationObj.put("body", "Body section");
            mainObj.put("notification", notificationObj);

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,"https://fcm.googleapis.com/fcm/send",
                    mainObj, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
                @Override
                public Map<String, String> getHeaders() {

                    Map<String, String> header = new HashMap<>();
                    header.put("content-type", "application/json");
                    header.put("authorization", "key="+key);//key = your Database Key
                    return header;
                }
            };
            requestQueue.add(jsonObjectRequest);
            //
        } catch (Exception ignored) {
        }

}
//send notification to other user above

要接收通知,请将此FCMService.class添加到您的项目中

public class FCMService extends FirebaseMessagingService {
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    //message is recieved. Do whatever you want to do 
}

@Override
public void onNewToken(@NonNull String s) {
            FirebaseMessaging.getInstance().subscribeToTopic("your topic name here").addOnSuccessListener(new OnSuccessListener<Void>() {//subcribe again if some error occured
        @Override
        public void onSuccess(Void aVoid) {
        }
    });
    super.onNewToken(s);
}

}

不要忘记在清单中注册。 manifest>application中添加以下代码

        <service
        android:name=".FCMService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

在应用程序源代码中添加firebase-key不是一个好主意。 您可以使用Firebase Cloud function [必须升级项目才能使用功能]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM