okHttp3ライブラリを使用してfirebaseにリクエストを送信し、特定のユーザに通知します。
RequestBody requestBody = null;
try {
requestBody = RequestBody.create(MEDIA_TYPE_JSON, getValidJsonBody().toString());
} catch (JSONException e) {
e.printStackTrace();
}
Request request = new Request.Builder()
.addHeader(CONTENT_TYPE, APPLICATION_JSON)
.addHeader(AUTHORIZATION, AUTH_KEY)
.url(FCM_URL)
.post(requestBody)
.build();
Call call = new OkHttpClient().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "onGetAllUsersFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful())
Log.e(TAG, "onResponse: " + response.body().string());
}
});
}
private JSONObject getValidJsonBody() throws JSONException {
JSONObject jsonObjectBody = new JSONObject();
jsonObjectBody.put(KEY_TO, mReceiverFirebaseToken);
JSONObject jsonObjectData = new JSONObject();
jsonObjectData.put(KEY_TITLE, mTitle);
jsonObjectData.put(KEY_TEXT, mMessage);
jsonObjectData.put(KEY_USERNAME, mUsername);
jsonObjectData.put(KEY_UID, mUid);
jsonObjectData.put(KEY_FCM_TOKEN, mFirebaseToken);
jsonObjectBody.put(KEY_DATA, jsonObjectData);
return jsonObjectBody;
}