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

标签 android firebase push-notification firebase-cloud-messaging retrofit

尝试使用 android 中的改造库发送 fcm 通知。我想向其他 Android 设备显示带有标题和消息的通知。 这是用于推送通知的代码和示例文件。

使用 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 类:

public class FirebaseMessage {
String to;
NotifyData notification;

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

通知数据类:

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。

最佳答案

模块:应用依赖

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

API客户端

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;
    }
}

API接口(interface)

public interface ApiInterface {

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

根模型

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;
    }
}

通知模型

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;
    }

}

数据模型

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;
    }

}

使用此方法发送通知

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) {

        }
    });
}

关于android - 在 android 中使用改造库发送 fcm 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117563/

相关文章:

android - MapView 中的致命和 NullPointerException

typescript - “查询”在类型 'QueryFn' 中不存在 | angularfire2

ios - 推送通知测试工作流程 [iOS]

Azure 通知中心 : What is Success and Failure Property in NotificationOutcome

ios - 如何知道推送通知发送状态

Android fragment - 指定的 child 已经有一个 parent 。您必须先对 child 的 parent 调用 removeView()

android - RecyclerView - 如何获得对每一行 View 的引用

android - MediaStore.Images.Media 降低存储到图库的图像质量

swift - 子类类型作为闭包参数

swift - Firebase Swift 3 从组中获取多个值