从应用程序发送firebase通知请求

时间:2017-05-09 10:38:13

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

我在Android应用中使用Firebase服务进行推送通知。该服务运行良好,我能够从firebase控制台管理员向所有用户和单个用户发送通知。

我的问题是:我想在用户在应用上发布帖子后发送自动通知(不使用管理员)。

  1. 用户发布帖子
  2. 使用用户ID
  3. 向firebase API发送请求
  4. Firebase生成任务通知(30分钟)并发送给用户
  5. 从哪里开始?有什么想法吗?

1 个答案:

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