티스토리 뷰

Android GCM Push메세지 전송하기.



최근 Android공부를 시작하면서 필요한 것들이 어떤 것들이 있나

생각하다 GCM관련된 부분이 어떻게 동작하는지 궁금하여 GCM

발송 Sample 코드를 통해 테스트를 진행해 보았다.

code.google.com에 Android GCM Client 예제 소스가 있으니 참고하면 된다. 


1. Android 소스 다운로드

Git Repository : https://code.google.com/p/gcm/

$ git clone https://code.google.com/p/gcm/


2. Project 생성 및 API Key 획득 

URL : https://console.developers.google.com

프로젝트 생성 후 발급받은 API Key를 GCM 서버에 등록한다.

[사진 1] 프로젝트 생성


[그림 2] API 키 생성 여부 확인 


3. 서버 API Key 등록

기본적으로 GCM Push를 발송하기 위해 각각의 Client를 구분하기 위해 

발급받는 RegistrationID 값, App을 인증하기 위한 API Key가 필요하다. 

RegistrationID는 동일 Client라도 랜덤하게 바뀔 수 있기 때문에 매 요청시 

Client로 부터 받아야하며 API Key의 경우 한번 발급받고 서버에 저장해 두면 된다.


서버 코드

Node.js를 이용하여 간단히 구현했으며, 설치를 원하시는 분은 

nvm (Node Version Manager)를 통해 설치 해 볼 것을 권장한다. 

URL : https://github.com/creationix/nvm


app.js

var gcm = require('node-gcm');

var message = new gcm.Message();

message.addData('key1', 'msg1');

var regIds = ['YOUR_REG_ID_HERE'];

var sender = new gcm.Sender('YOUR_API_KEY_HERE');

sender.send(message, regIds, function (err, result) {
    if(err) console.error(err);
    else    console.log(result);
});


Android Client Code

GcmIntentService.java 파일의 내부를 수정하여 Push Notification 부분을 추가한다.

[그림 3] GCM Client Package 구조


서버에서 Push를 발송하면 GcmBroadcastReceiver로 전달 후 

onHandleIntent로 전달 하기 때문에 getExtras로 데이터를 받은 후 출력

방식에 대해 구현해주도록 한다.

GcmIntentService.java

@Override

    protected void onHandleIntent(Intent intent) {

        Bundle extras = intent.getExtras();

        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        // The getMessageType() intent parameter must be the intent you received

        // in your BroadcastReceiver.

        String messageType = gcm.getMessageType(intent);

        System.out.println("##### messageType : " + messageType);

        System.out.println("##### extras : " + extras.toString());



        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle

            /*

             * Filter messages based on message type. Since it is likely that GCM will be

             * extended in the future with new message types, just ignore any message types you're

             * not interested in, or that you don't recognize.

             */

            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {

                sendNotification("Send error: " + extras.toString());

            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {

                sendNotification("Deleted messages on server: " + extras.toString());

            // If it's a regular GCM message, do some work.

            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

                // This loop represents the service doing some work.

                /*

                for (int i = 0; i < 5; i++) {

                    Log.i(TAG, "Working... " + (i + 1)

                            + "/5 @ " + SystemClock.elapsedRealtime());

                    try {

                        Thread.sleep(5000);

                    } catch (InterruptedException e) {

                    }

                }

                */

                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

                // Post notification of received message.

                sendNotification("Received: " + extras.toString());

                Log.i(TAG, "Received: " + extras.toString());

                Log.i(TAG, "#### Title : " + extras.get("title"));

                Log.i(TAG, "#### Message : " + extras.get("message"));

            }

        }

        // Release the wake lock provided by the WakefulBroadcastReceiver.

        GcmBroadcastReceiver.completeWakefulIntent(intent);

sendNotification을 통해 Push Message 내용을 출력한다.


RegistrationID는 아래 소스를 참조하면 구할 수 있다.


DemoActivity.java 

private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGcmPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.i(TAG, "Registration not found.");
        return "";
    }
    // Check if app was updated; if so, it must clear the registration ID
    // since the existing regID is not guaranteed to work with the new
    // app version.
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.i(TAG, "App version changed.");
        return "";
    }
    return registrationId;
} 


RegistrationID 와 API Key를 서버에 전송 후 푸시를 보내면 아래와 같이

Push 수신이 가능하다.

[그림 4] GCM Push 메세지 확인창

댓글