Friday, December 9, 2011

Android C2DM client 예제


준비물 : c2dm account(파이썬으로 c2dm서버 만들기 포스팅 참조)

만들 예제의 패키지 구조

우선 Manifest file의 Code



    

    
        
            
                

                
            
        
        
        
  
   
   
    
    
   
   
   
    
    
   
  
  
    
 
 
 

 
 



중요한 부분:
15~ 28 line <-com.leehack.c2dmtest.push.C2DMReceiver 등록
31~36 line <- C2DM을 사용할 수 있도록 어플에 permission부여

C2DMReceiver.java: 리시버 작성

package com.leehack.c2dmtest.push;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

public class C2DMReceiver extends BroadcastReceiver {
 static String registration_id = null;
 private Context mContext;
 @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);
  }
 }
 //서버에 등록이 되면 Registration_id를 C2DM서버에서 보내준다. 받은 이 ID를 별도로 구성한 서버에 보내야 한다.
 private void handleRegistration(Context context, Intent intent) {
  String registration = intent.getStringExtra("registration_id");
  if (intent.getStringExtra("error") != null) {
   // Registration failed, should try again later.
  } else if (intent.getStringExtra("unregistered") != null) {
   registration = null;
  } else if (registration != null) {
   registration_id = registration;
   mContext = context;
   SharedPreferences sp  = mContext.getSharedPreferences("com.leehack.c2dmtest", Activity.MODE_PRIVATE);
   SharedPreferences.Editor ed = sp.edit();
   ed.putString("registration_id", registration_id);
   ed.commit();
   Toast toast = Toast.makeText(context, "Registration Id\n" + registration_id,
     Toast.LENGTH_LONG);
   toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
   toast.show();
   Log.d("C2DMReceiver", "c2dm registered");
  }
 }
 //메세지가 도착하면 토스트로 도착한 메세지를 보여줌
 private void handleMessage(Context context, Intent intent) {

  String c2dm_msg = intent.getExtras().getString("msg");

  System.out.println("c2dm_msg======>" + c2dm_msg);
  Toast toast = Toast.makeText(context, "c2dmMessage\n" + c2dm_msg,
    Toast.LENGTH_LONG);
  toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
  toast.show();

 }
}

PushHelper.java: c2dm 서버에 Register/Unregister 메소드 작성

package com.leehack.c2dmtest.push;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class PushHelper {

 final static String c2dmDevId = "c2dm에 등록한 account";
 
 public static void c2dmRegister(Context context){
  SharedPreferences sp  = context.getSharedPreferences("com.leehack.c2dmtest", Activity.MODE_PRIVATE);
  if(sp.getString("registration_id", null) != null)
   return;
  Intent registrationIntent = new Intent(
    "com.google.android.c2dm.intent.REGISTER");
  registrationIntent.putExtra("app",
    PendingIntent.getBroadcast(context, 0, new Intent(), 0));
  registrationIntent.putExtra("sender", c2dmDevId);
  context.startService(registrationIntent);
 }
 public static void c2dmUnregister(Context context){
  Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
  unregIntent.putExtra("app", PendingIntent.getBroadcast(context, 0, new Intent(), 0));
  context.startService(unregIntent);
 }
}


C2DM_TESTActivity.java: Register와 Unregister버튼의 동작을 정의

package com.leehack.c2dmtest;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

import com.leehack.c2dmtest.push.PushHelper;

public class C2DM_TESTActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    PushHelper.c2dmRegister(C2DM_TESTActivity.this);
   }
  });
        findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    PushHelper.c2dmUnregister(C2DM_TESTActivity.this);
   }
  });
    }
}

앞으로 해야 할일!
1. 구글의 C2DM과 통신한 Push Server 구성
2. Register를 한 후 C2DMReceiver를 통해 C2DM 서버로 부터 전달받은 Registration_ID를 구성한 Push Server로 전달하는 로직 구성
(파이썬으로 c2dm서버 만들기 포스팅을 참조하면 1번은 해결될 것이고 2번만 추가로 구성하면 된다)

No comments:

Post a Comment