- GCM은 사용하지 말것.
https://developers.google.com/cloud-messaging/
- FCM 레퍼런스 :
https://firebase.google.com/docs/cloud-messaging/migrate-v1?hl=ko
- 예제소스는 HTTP v1 샘플소스
- 메시지 포멧은 JSON 이므로 JSON 라이브러리를 사용을 권장.
1. 메시지 전송
- 기본코드
String urlStr = "https://fcm.googleapis.com/fcm/send";
String authorization = "key=[클라우드 메시지 서버 키]";
String token = "[클라이언트 FCM 토큰]";
String data = "\"data\": {\r\n" + " \"en\": \"abc\",\r\n" + " \"ko\": \"가나다\"\r\n" + " }";
String notification = "\"notification\" : {\r\n"
+ " \"body\" : \"This is an FCM notification message!\",\r\n"
+ " \"title\" : \"FCM Message\"\r\n" + " }";
URL url = null;
HttpURLConnection connection = null;
BufferedOutputStream bos = null;
BufferedReader reader = null;
try {
url = new URL(urlStr);
connection = urlStr.startsWith("https://") ? (HttpsURLConnection) url.openConnection()
: (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.setRequestProperty("cache-control", "no-cache");
connection.setRequestProperty("Authorization", authorization);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
bos = new BufferedOutputStream(connection.getOutputStream());
String message = "{\"to\" : \"" + token + "\"," + data + "," + notification + "}";
bos.write(message.getBytes("UTF-8"));
bos.flush();
bos.close();
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
StringBuffer buffer = null;
if (responseCode == HttpURLConnection.HTTP_OK) {
buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String temp = null;
while ((temp = reader.readLine()) != null) {
buffer.append(temp);
}
reader.close();
}
connection.disconnect();
System.out.println(String.format("Response : %d, %s", responseCode, responseMessage));
System.out.println("Response DATA : ");
System.out.println(buffer == null ? "NULL " : buffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
> POST 전송 방식
> data만 사용하면 항상 백그라운드 서비스가 메시지를 수신
> notification을 적용할 경우 Activity가 Foreground 상태일 때와 Background 상태일 때 응답 방식이 변경됨.
> 한글깨짐 문제가 될 수 있으므로 UTF-8 인코딩을 적용.