GCM 구현2 - 서버

 

 

안드로이드 : http://ghj1001020.tistory.com/783?category=719597

서버 : http://ghj1001020.tistory.com/784?category=756570

 

 

가이드 : https://developers.google.com/cloud-messaging/http

 

1. 앱은 GCM 토큰을 가져와서 앱에 저장합니다

2. 서버에서 앱에 저장된 GCM 토큰을 사용하여 메시지를 요청합니다

3. 앱이 GCM 메시지 수신하고 알림을 띄웁니다

* 테스트 용도 이므로 토큰을 서버에 저장하는 부분은 제외했습니다. (서버에서는 디바이스의 GCM 토큰을 하드코딩해서 보냅니다)

 

 

1. gcm-server 라이브러리 이용

 

pom.xml

1
2
3
4
5
6
7
        <!-- GCM -->
        <!-- https://mvnrepository.com/artifact/com.google.gcm/gcm-server -->
        <dependency>
            <groupId>com.google.gcm</groupId>
            <artifactId>gcm-server</artifactId>
            <version>1.0.0</version>
        </dependency>
cs

* 라이브러리 jar 파일을 받아서 사용하실때는 json-simple 라이브러리도 필요합니다

* https://github.com/google/gcm/tree/master/client-libraries/java/rest-client/src/com/google/android/gcm/server

 

 

GcmSender.java

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
    //GCM Url
    private final String GCM_URL = "https://gcm-http.googleapis.com/gcm/send";
 
    ...
 
    //GCM 전송 - 라이브러리 사용
    public void gcmSend(Map<StringString> datas) {
        Message.Builder builder = new Message.Builder();
        builder.delayWhileIdle(true);    //기기가 절전 상태에서도 수신될지 여부
        builder.timeToLive(60*1000);    //기기가 비활성화 상태일때 메시지 유효시간 (초)
        builder.collapseKey(UUID.randomUUID().toString());    //중복메시지도 전송될 수 있도록 고유키 생성
        //데이터 추가
        builder.addData( "title", datas.get("title") );
        builder.addData( "body", datas.get("body") );
 
        //메시지 생성
        Message message = builder.build();
        
        //단말 토큰 리스트 
        ArrayList<String> registIdList = new ArrayList<>();
        registIdList.add(REG_ID);
                
        try {
            Sender sender = new Sender(SERVER_KEY);
            MulticastResult multiResult = sender.send(message, registIdList, 1);    //retry 1회
            List<Result> resultList = multiResult.getResults();
            //결과출력 
            for( Result result : resultList ) {
                if( result.getMessageId() != null ) {
                    //성공
                    System.out.println("Success");
                }
                else {
                    //실패
                    System.out.println("Fail : "+result.getErrorCodeName());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
cs

* SERVER_KEY(서버키) 와 REG_ID(토큰) 는 각자 테스트 하시는 걸로 사용합니다

 

 

2. HttpsURLConnection 사용

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
    //GCM 전송 - HttpsUrlConnection 사용
    public void gcmSendUrl(Map<StringString> datas) {
        try {
            URL url = new URL(GCM_URL);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestProperty("Authorization""key="+SERVER_KEY);
            conn.setRequestProperty("Content-Type""application/json; UTF-8");
            
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            JSONObject jsonMsg = new JSONObject();
            jsonMsg.put( "title", datas.get("title") );
            jsonMsg.put( "body", datas.get("body") );
            
            JSONObject json = new JSONObject();
            json.put("to", REG_ID);
            json.put("delay_while_idle"true);
            json.put("data", jsonMsg);
 
            System.out.println("Param : "+json.toString());
            
            conn.setRequestProperty("Content-Length"String.valueOf(json.toString().length()));
            
            //보내기
            OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            osw.write(json.toString());
            osw.flush();
            osw.close();
 
            //받기
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
             
            StringBuffer strBuf = new StringBuffer();
            String inputLine;
            while((inputLine = in.readLine()) != null) { // response 출력
                strBuf.append(inputLine);
            }
            
            in.close();
            conn.disconnect();    
            
            //결과
            if(!strBuf.toString().isEmpty()) {
                System.out.println("Result : "+strBuf.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
cs

 

 

main

1
2
3
4
5
6
7
8
9
10
    public static void main(String[] args) {
        GcmSender gcmSender=  new GcmSender();
        //데이터
        Map<StringString> datas = new HashMap<>();
        datas.put("title""GCM 테스트");
        datas.put("body""GCM 테스트 중입니다.");
        
        gcmSender.gcmSend(datas);
//        gcmSender.gcmSendUrl(datas);
    }
cs

* title과 body 처럼 어떤 키-값으로 보낼지는 클라이언트와 미리 약속이 되어 있어야 합니다

 

 

결과

* 서버에서 전송한 GCM 메시지를 안드로이드에서 수신하여 알림으로 띄웠습니다

+ Recent posts