我在Android应用中使用Firebase服务进行推送通知。该服务运行良好,我能够从firebase控制台管理员向所有用户和单个用户发送通知。
我的问题是:我想在用户在应用上发布帖子后发送自动通知(不使用管理员)。
从哪里开始?有什么想法吗?
答案 0 :(得分:0)
使用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;
}