안드로이드 FCM 푸시서버 예제
안녕하세요. 지난번에 firebase 안드로이드 FCM 푸시 관련하여 알아보았습니다.
오늘은 밑도 끝도 없이 예제를 통해서 간단한 사용법을 배워보죠!
***htttp V1 사용법이 아닙니다. 구글에서 말하는 기존의 구형 원시 사용법입니다.
예제는 간단합니다.
1 2 3 4 5 | //구글 인증 서버키 private final String AUTH_KEY_FCM = "AAAAlTG6ylg:APA91bHo8 ... "; private final String API_URL_FCM = "https://fcm.googleapis.com/fcm/send"; //기기별 앱 토큰 private String userDeviceIdKey = "d-tse-wQXDA:APA91bH ..."; | cs |
인증서버키를 가지고 있구요. 예제니까 단순하게 기기별 발급된 토큰을 가지고 있습니다. (앱에서 구현하여 받은 토큰)
1 2 3 4 5 6 7 8 | url = new URL(API_URL_FCM); conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM); conn.setRequestProperty("Content-Type", "application/json"); | cs |
http 통신을 위한 커넥션도 오픈해줍니다.
1 | JsonObject json = new JsonObject(); | cs |
Json 으로 통신할거니까 객체생성 해주시구요.
1 2 3 4 | JsonObject pushData = new JsonObject(); pushData.addProperty("pushTitle", "1111111"); pushData.addProperty("pushImageUrl", ""); pushData.addProperty("pushLinkYn", ""); | cs |
이렇게 저렇게 JSON 가공해서 해당 url로 보내기! 끝~ 입니다.
* 큰그림 : http통신 -> 구글로 던진다 -> 구글 FCM 에서 토큰별로 푸시를 쏜다 -> 앱에서 받는다
이렇게 간단하게 구형이 가능합니다. 아래의 예제를 참고하시길~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | public class FcmPushTest { //구글 인증 서버키 private final String AUTH_KEY_FCM = "AAAAlTG6ylg:APA91..."; private final String API_URL_FCM = "https://fcm.googleapis.com/fcm/send"; //기기별 앱 토큰 private String userDeviceIdKey = "d-tse-wQXDA:APA..."; private HttpURLConnection conn; private OutputStreamWriter wr; private BufferedReader br; private URL url; public FcmPushTest(){ } /** * 구글서버로 푸시 request * pushFCMNotification * @throws Exception */ public void pushFCMNotification(String msgBody) throws Exception { /* 기본적인 페이로드 전송시 { "data": { "score": "5x1", "time": "15:10" }, "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." } 선택적인 필드의 조합시 { "collapse_key": "score_update", "time_to_live": 108, "data": { "score": "4x8", "time": "15:16.2342" }, "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." } */ //if(pushKeyAuth()){ url = new URL(API_URL_FCM); conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM); conn.setRequestProperty("Content-Type", "application/json"); //일반 텍스트 전달시 Content-Type , application/x-www-form-urlencoded;charset=UTF-8 //알림 + 데이터 메세지 형태의 전달 JsonObject json = new JsonObject(); JsonObject info = new JsonObject(); JsonObject dataJson = new JsonObject(); //앱 백그라운드 발송시 기본noti는 이 내용을 참조한다 info.addProperty("title", "알림"); info.addProperty("body", msgBody); // Notification body info.addProperty("sound", "default"); //noti 알림 부분 json.add("notification", info); //디바이스전송 (앱단에서 생성된 토큰키) json.addProperty("to", userDeviceIdKey); // deviceID //json.addProperty("to", "/topics/" + topicsKey); //여러주제 전송 //"condition": "'dogs' in topics || 'cats' in topics", //데이터 페이로드 //푸시수신후 다음 로직 처리를 위한 데이터 /*type1 의 경우*/ //dataJson.addProperty("type", "aqua"); //dataJson.addProperty("message", "아쿠아필드 순번대기 메세지"); //dataJson.addProperty("bcn_cd", "02"); /*type2 의 경우---------------------------------*/ dataJson.addProperty("type", "PK"); dataJson.addProperty("message", "type2 푸시 메세지"); dataJson.addProperty("bcn_cd", "02"); JsonObject pushData = new JsonObject(); pushData.addProperty("pushTitle", "1111111"); pushData.addProperty("pushImageUrl", ""); pushData.addProperty("pushLinkYn", ""); pushData.addProperty("pushLinkType", ""); pushData.addProperty("pushLinkSeq", ""); pushData.addProperty("bcnCd", ""); pushData.addProperty("bcnNm", ""); pushData.addProperty("pushPopTitle1", ""); pushData.addProperty("pushPopTitle2", ""); pushData.addProperty("pushSeq", ""); dataJson.add("pushData", pushData); /*type2 의 경우---------------------------------*/ json.add("data", dataJson); try{ wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); wr.write(json.toString()); wr.flush(); }catch(Exception e){ connFinish(); throw new Exception("OutputStreamException : " + e); } if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { //400, 401, 500 등 connFinish(); throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); }else{ br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } //200 + error 는 재전송 등등의 로직 } //} } /** * 네트웍크관련 finalize * connFinish */ private void connFinish(){ if(br != null){ try { br.close(); br = null; } catch (IOException e) { } } if(wr != null){ try { wr.close(); wr = null; } catch (IOException e) { } } if(conn != null){ conn.disconnect(); conn = null; } } } | cs |
*파트너스 활동을 통해 일정액의 수수료를 제공받을 수 있음
'HELLO_WORLD > 안드로이드_Android' 카테고리의 다른 글
[지식공유] firebase 를 이용한 안드로이드 채팅앱 (0) | 2018.10.21 |
---|---|
[지식공유] 안드로이드 메모리 관리는 어떻게 ? (누수 예방법) (0) | 2018.10.20 |
[지식공유] 안드로이드 FCM 푸시서버 예제 (0) | 2018.10.20 |
[지식공유] 안드로이드 FCM 푸시서버 구현 (0) | 2018.10.16 |
[지식공유] 안드로이드 GCM을 FCM로 마이그레이션 해봅시다 (0) | 2018.10.16 |
[지식공유] 안드로이드 8.0(api26) 알림채널 생성하기 (notification channel) (0) | 2018.10.14 |
댓글0