Last active
March 2, 2020 09:08
-
-
Save Gongcu/668dbcc4307f9a71ac342d2d3da1a05a to your computer and use it in GitHub Desktop.
FCM - okHttp, Json, Gson, 싱글톤 패턴
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.example.healthtagram.fcm; | |
| public class FCMpush { | |
| private static final MediaType mediaType = MediaType.parse("application/json; charset=utf-8"); | |
| private static final String uri = "https://fcm.googleapis.com/fcm/send"; | |
| private static final String serverKey = "AIzaSyD...."; | |
| private Gson gson; | |
| private OkHttpClient httpClient; | |
| //싱글톤 패턴을 위해 생성사를 private으로 선언 | |
| private FCMpush(){ | |
| gson = new Gson(); | |
| httpClient = new OkHttpClient(); | |
| } | |
| //싱글톤 패턴 | |
| public static FCMpush getInstance(){ | |
| return new FCMpush(); | |
| } | |
| public void sendMessage(String destinationUid, final String title, final String message){ | |
| FirebaseFirestore.getInstance().collection("tokens").document(destinationUid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { | |
| @Override | |
| public void onComplete(@NonNull Task<DocumentSnapshot> task) { | |
| if(task.isSuccessful()){ | |
| String token = task.getResult().get("token").toString(); | |
| PushData pushData = new PushData(token); | |
| pushData.getNotification().setBody(message); | |
| pushData.getNotification().setTitle(title); | |
| //okhttp를 이용한 http 통신 | |
| RequestBody body = RequestBody.create(mediaType,gson.toJson(pushData)); | |
| Request request = new Request.Builder().addHeader("Content-Type","application/json") | |
| .addHeader("Authorization","key="+serverKey) | |
| .url(uri).post(body).build(); | |
| httpClient.newCall(request).enqueue(new Callback() { | |
| @Override | |
| public void onFailure(Call call, IOException e) { | |
| } | |
| @Override | |
| public void onResponse(Call call, Response response) throws IOException { | |
| Log.e("DD",response.body().string()); | |
| } | |
| }); | |
| } | |
| } | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment