티스토리 뷰

[Android] C2DM, 푸시 알림 구현하기.


안드로이드에서는 C2DM (Cloud to Device Messaging)이 iOS에서의 푸시 알림과 같은 개념으로 사용자에게 알림 메세지를 서버에서 보내는 방식을 취하고 있다.


자세한 정보는 http://code.google.com/android/c2dm/index.html 에 가면 얻을 수 있다.


단계적으로 구현하는 방법을 알아보자.





1. C2DM을 이용하기 위한 등록


먼저 http://code.google.com/android/c2dm/signup.html 가서 앱을 등록해야한다. 입력해야하는 정보는


- 개발하고 있는 안드로이드앱의 패키지(예 : com.example.app)

- 하루에 이용할 메세지의 수

- 초당 이용할 메세지의 수

- 이메일 연락처

- 메세징에서 이용할 구글 계정

- 문제 발생시의 긴급 연락처


등록은 하루 정도 걸리니 일단 등록부터 하고 소스를 구현하자.


2. AndroidManifest.xml 설정하기


: 아래에 com.example.myapp를 자기의 패키지에 맞도록 하면 된다.

: .C2DMReceiver는 나중에 메세지를 받을때 처리하게 될 클래스이다.

<manifest package="com.example.myapp" ...>

   
<!-- Only this application can receive the messages and registration result -->
   
<permission android:name="com.example.myapp.permission.C2D_MESSAGE" android:protectionLevel="signature" />
   
<uses-permission android:name="com.example.myapp.permission.C2D_MESSAGE" />

   
<!-- This app has permission to register and receive message -->
   
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

   
<!-- Send the registration id to the server -->
   
<uses-permission android:name="android.permission.INTERNET" />

   
<application...>
     
<!-- Only C2DM servers can send messages for the app. If permission is not set - any other app can generate it -->
     
<receiver android:name=".C2DMReceiver" android:permission="com.google.android.c2dm.permission.SEND">
         
<!-- Receive the actual message -->
         
<intent-filter>
             
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
             
<category android:name="com.example.myapp" />
         
</intent-filter>
         
<!-- Receive the registration id -->
         
<intent-filter>
             
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
             
<category android:name="com.example.myapp" />
         
</intent-filter>
     
</receiver>
      ...
   
</application>
   ...
</manifest>

- 각 태그의 위치를 잘 보고 잘 설정하자.


3. C2DM서버에 이 앱을 Registration을 한다.

: 이 부분은 처음 시작하는 Activity에 넣어두면 된다. 나중에 다른 Utility 클래스 등으로 분리 시켜도 된다.
Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registrationIntent
.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); // boilerplate
registrationIntent
.putExtra("sender", emailOfSender);
startService
(registrationIntent);


4. C2DM서버에서 unregister 하는 소스

: 반대로 등록을 해제하는 방법은 아래와 같다. 앱에 설정 화면을 넣어서 알림 해제등을 하면 다음과 같이 실행하면 된다.
Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
unregIntent
.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
startService
(unregIntent);



5. Manifest에서 설정한 Receiver 구현하기


: BroadcastReceiver 를 확장하는 클래스를 구현한다.

: onReceive 함수를 오버라이드 해서 받는 다.



package gt.smartpkg.client;


import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences.Editor;

import android.util.Log;


public class C2DMReceiver extends BroadcastReceiver {

private static String KEY = "c2dmPref";

private static String REGISTRATION_KEY = "registrationKey";

@Override

public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {

        handleRegistration(context, intent);

    } else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {

        handleMessage(context, intent);

    }

}


private void handleRegistration(Context context, Intent intent) {

    String registration = intent.getStringExtra("registration_id"); 

    if (intent.getStringExtra("error") != null) {

        // Registration failed, should try again later.

    Log.d("c2dm", "registration failed");

    String error = intent.getStringExtra("error");

    Log.d("c2dm" , error);

    } else if (intent.getStringExtra("unregistered") != null) {

        // unregistration done, new messages from the authorized sender will be rejected

    Log.d("c2dm", "unregistered");

    } else if (registration != null) {

      // Send the registration ID to the 3rd party site that is sending the messages.

      // This should be done in a separate thread.

      // When done, remember that all registration is done. 

    Log.d("c2dm", registration);

    Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();

    editor.putString(REGISTRATION_KEY, registration);

editor.commit();

    }

}

private void handleMessage(Context context, Intent intent)

{

//Do whatever you want with the message

}

}



:  여기서 registration_id를 받았으면 바로 서버로 보내서 해당 사용자의 정보에 업데이트를 하는 것이 좋다.

: handleMessage 안에는 Notification을 이용하는 것이 좋다.


- 여기까지가 클라이언트의 안드로이드 앱에서 설정해야하는 것들이다.


- 다음에는 서버에서 메세지를 클라이언트에게 보내는 방법을 알아보자.


끝.


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
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
글 보관함