简体   繁体   English

使用android中的改造库发送fcm推送通知

[英]sending fcm push notifications using retrofit library in android

Trying to send fcm notifications using retrofit library in android.尝试使用 android 中的改造库发送 fcm 通知。 I want to show notification with title and message to other android device.我想向其他 Android 设备显示带有标题和消息的通知。 Here is the code and sample files used for push notification.这是用于推送通知的代码和示例文件。

Function to Send Push Notification Using Retrofit Call:使用改造调用发送推送通知的功能:

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 Class: FirebaseMessage 类:

public class FirebaseMessage {
String to;
NotifyData notification;

public FirebaseMessage(String to, NotifyData notification) {
    this.to = to;
    this.notification = notification;
}

} }

NotifyData Class:通知数据类:

public class NotifyData {
String title;
String body;
public NotifyData(String title, String body ) {

this.title = title;
this.body = body;
}

}

FirebaseClient Class: 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 Class: FirebaseApi 类:

public interface FirebaseApi {
@Headers({"Authorization: key=Legacy Service Key",
        "Content-Type:application/json"})
@POST("fcm/send")
Call<FirebaseMessage> sendMessage(@Body FirebaseMessage message);
}

In MyFirebaseMessagingService Class:在 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);
}

But it shows blank notification every time with null title and null body.但它每次都显示空标题和空正文的空白通知。 How to retreive my notifydata through remoteMessage Properly.如何正确地通过 remoteMessage 检索我的通知数据。

Module:app dependencies模块:应用程序依赖项

implementation 'com.squareup.retrofit2:retrofit:2.6.0'
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'

ApiClient客户端

public class ApiClient {

    private static final String BASE_URL = "https://fcm.googleapis.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

ApiInterface接口

public interface ApiInterface {

    @Headers({"Authorization: key=" + ConstantKey.SERVER_KEY, "Content-Type:application/json"})
    @POST("fcm/send")
    Call<ResponseBody> sendNotification(@Body RootModel root);
}

RootModel根模型

public class RootModel {

    @SerializedName("to") //  "to" changed to token
    private String token;

    @SerializedName("notification")
    private NotificationModel notification;

    @SerializedName("data")
    private DataModel data;

    public RootModel(String token, NotificationModel notification, DataModel data) {
        this.token = token;
        this.notification = notification;
        this.data = data;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public NotificationModel getNotification() {
        return notification;
    }

    public void setNotification(NotificationModel notification) {
        this.notification = notification;
    }

    public DataModel getData() {
        return data;
    }

    public void setData(DataModel data) {
        this.data = data;
    }
}

NotificationModel通知模型

public class NotificationModel {

    private String title;
    private String body;

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

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}

DataModel数据模型

public class DataModel {

    private String name;
    private String age;

    public DataModel(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

}

Send notification by using this method使用此方法发送通知

private void sendNotificationToUser(String token) {
    RootModel rootModel = new RootModel(token, new NotificationModel("Title", "Body"), new DataModel("Name", "30"));

    ApiInterface apiService =  ApiClient.getClient().create(ApiInterface.class);
    retrofit2.Call<ResponseBody> responseBodyCall = apiService.sendNotification(rootModel);

    responseBodyCall.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            Log.d(TAG,"Successfully notification send by using retrofit.");
        }

        @Override
        public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {

        }
    });
}

Whoah, when i try a answer from @Mustofa Kamal.哇,当我尝试@Mustofa Kamal 的回答时。 i got problem about model because i got error code 400 that's mean error parsing with format JSON.我遇到了关于模型的问题,因为我得到了错误代码 400,这意味着使用 JSON 格式解析错误。 so that, i use JsonObject as data parsing into json format like this所以,我使用 JsonObject 作为数据解析成这样的 json 格式

JsonObject jNotif = new JsobObject()
jNotif.addProperly("title","hello world");
jNotif.addProperly("body","hello this world");

JsonObject jFCM = new JsonObject()
jFCM.add("notification",jNotif);
jFCM.addProperly("to",<your_token_from_firebase>);

and i use in ApiInterface interface like this :我在 ApiInterface 接口中使用如下:

@Headers({"Content-Type: application/json","Authentication: <your_server_key>"})
@POST("/fcm/send")
Call<<your_model_response>> createFirebaseCloudM(@Body <your_model_class>);

i include that code in method fill retrofit response.我将该代码包含在方法填充改造响应中。 i know you how about handle a response from retrofit and it same with above answer.我知道你如何处理改造的响应,它与上述答案相同。 but, without model when you send a data但是,当您发送数据时没有模型

hope it will be help...希望它会有所帮助...

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

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