firebase 通过FCM发送推送通知- Android

jjhzyzn0  于 2023-03-09  发布在  Android
关注(0)|答案(1)|浏览(192)

我正在处理的应用程序中,我想发送推送通知给特定用户
我拿到他的代币了,存起来。
也得到了我的API密钥。
我尝试用postman发送POST请求,它成功地完成了,我想在我的代码中以编程方式完成它

private void notif(){
String json = "{\"to\": \"<USER_FCM>\",\"notification\": {\"title\": \"Check this Mobile (title)\",\"body\": \"Rich Notification testing (body)\"}";

CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
    JSONObject jsonObject = new JSONObject(json);
} catch (JSONException e) {
    e.printStackTrace();
}

try {
    HttpPost request = new HttpPost("https://fcm.googleapis.com/fcm/send");
    StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ", ContentType.APPLICATION_JSON);
    request.addHeader("content-type", "application/json");
    request.addHeader("Authorization","key=<API_KEY>");
    request.setEntity(params);
    HttpResponse response;
    response = httpClient.execute(request);
    String test = response.getEntity().getContent().toString();
    Log.d("RESPONSESS",test);

}catch (Exception ex) {

} finally {
    try {
        httpClient.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}
先谢了

ddarikpa

ddarikpa1#

下面是我如何将推送通知发送到特定的移动的令牌。我希望它能有所帮助,

Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\r\n   \"to\" : \""+mobileToken+"\",\r\n   \"data\" : {\r\n     \"Action\" : \"on\"\r\n   }\r\n } ");
            Request request = new Request.Builder()
                    .url("https://fcm.googleapis.com/fcm/send")
                    .method("POST", body)
                    .addHeader("Authorization", "key=AuthKEY")
                    .addHeader("Content-Type", "application/json")
                    .build();
            try {
                Response response = client.newCall(request).execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    t1.start();

依赖,

implementation 'io.grpc:grpc-okhttp:1.30.0'

相关问题