Skip to content

Instantly share code, notes, and snippets.

@Gongcu
Last active March 2, 2020 09:08
Show Gist options
  • Select an option

  • Save Gongcu/668dbcc4307f9a71ac342d2d3da1a05a to your computer and use it in GitHub Desktop.

Select an option

Save Gongcu/668dbcc4307f9a71ac342d2d3da1a05a to your computer and use it in GitHub Desktop.
FCM - okHttp, Json, Gson, 싱글톤 패턴
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