본문 바로가기

분노=프로그래밍/Android

GCM 이용하기 2/3

Google Cloud Messaging for Android

앞서 Google Cloud Messaging이 무엇인지에 대해 알아보았다.
이제부터는 실제 구현한 샘플 소스를 통해 어떻게 사용할 수 있는지 알아보도록 한다.


GCM 메시지 발송을 하기 위해선 Registration Id를 필요로 하므로 GCM 적용을 통해

RegistrationId 발급 및 메시지 처리를 구현한 어플리케이션에 소스를 첨부하니 참고 바란다.

구현 순서는 다음과 같다.


1.어플리케이션 프로젝트 내 GCM ID 발급 요청 프로세스 
2.GCM Cloud Message를 처리하기 위해 GCMBaseIntentService를 상속한 GCMIntentService의 구현


 1. MainActivity.java - 어플리케이션 내 GCM ID 발급 요청 프로세스
package com.leminity.gcmsampleapp;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;

/**
 * GCM Service 이용을 위한 샘플 프로젝트
 * @author Leminity
 *
 */
public class MainActivity extends Activity {
	
	private static final String TAG ="MainActivity";
	private static final String PROJECT_ID=""; //Google Cloud Messageing Service PROJECT ID
	private Context appContext = null;//applicationContext
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initialize();//변수 초기화
		startGCM();//GCM 시작 메소드
	}
	
	private void initialize(){
		appContext = getApplicationContext();
	}
	
	/**
	 * GCM 서비스를 시작한다.
	 */
	private void startGCM(){
		
		/**
		 * GCM Service가 이용 가능한 Device인지 체크한다.
		 * api 8(Android 2.2) 미만인 경우나 GCMService를 이용할 수 없는
		 * 디바이스의 경우 오류를 발생시키니 반드시 예외처리하도록 한다.
		 */
		try {
			GCMRegistrar.checkDevice(appContext);
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "This device can't use GCM");
			return;
		}
		
		
		/**
		 * 2.SharedPreference에 저장된 RegistrationID가 있는지 확인한다.
		 * 없는 경우 null이 아닌 ""이 리턴
		 */
		String regId = GCMRegistrar.getRegistrationId(appContext);
		
		/**
		 * Registration Id가 없는 경우(어플리케이션 최초 설치로 발급받은 적이 없거나,
		 * 삭제 후 재설치 등 SharedPreference에 저장된 Registration Id가 없는 경우가 이에 해당한다.)
		 */
		if(CommonUtils.isEmpty(regId)){
			/**
			 * 3.RegstrationId가 없는 경우 GCM Server로 Regsitration ID를 발급 요청한다.
			 * 발급 요청이 정상적으로 이루어진 경우 Registration ID는 SharedPreference에 저장되며,
			 * GCMIntentService.class의 onRegistered를 콜백한다.
			 */
			GCMRegistrar.register(appContext, PROJECT_ID);
			
		//SharedPreference에 저장된 Registration Id가 존재하는 경 
		}else{
			Toast.makeText(appContext, "Exist Registration Id: " + regId, Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		/**
		 * 4.앱 종료되기 전이나 종료하기 전에 GCMRegistrar.onDestroy를 반드시 호출한다.
		 * 호출하지 않을 경우 unRegisterReceiver오류가 발생한다.
		 * 해당 함수는 null이나 기타 오류에 대해 내부적으로 예외 처리하고 있으므로, 아무때나 마음껏 호출해도 된다.
		 */
		GCMRegistrar.onDestroy(appContext);
		super.onDestroy();
	}

}

2.GCM을 통해 수신한 Registration ID 및 Message 처리를 위한 소스이다.
 GCMIntentService.class는 반드시 GCMIntentService라는 이름으로 생성되어야 하며,
 어플리케이션 루트 패키지에 위치해야 한다. 상세한 내용은 소스 내 주석을 확인한다.

package com.leminity.gcmsampleapp; import android.content.Context; import android.content.Intent; import com.google.android.gcm.GCMBaseIntentService; /** * GCMBaseIntentService를 상속받은 클래스를 프로젝트 루트 패키지에 생성한다. * 클래스는 반드시 다음 조건을 충족해야 한다. * * 1.클래스명은 GCMIntentService여야 한다. * 2.반드시 루트 패키지 내에 선언되어 있어아 한다. * 상기 1,2 조건을 만족해야 하는 이유는 라이브러리 내에서 GCMService를 시작하는 부분이 * 'GCMIntentService'라는 명칭으로 하드코딩되어 적용되어 있다. * @author Leminity * */ public class GCMIntentService extends GCMBaseIntentService { /** * GCM Server로부터 발급받은 Project ID를 통해 SuperClass인 * GCMBaseIntentService를 생성해야한다. */ public GCMIntentService() { super(Constants.PROJECT_ID); // TODO Auto-generated constructor stub } @Override protected void onError(Context arg0, String arg1) { // TODO Auto-generated method stub /** * GCM 오류 발생 시 처리해야 할 코드를 작성한다. * ErrorCode에 대해선 GCM 홈페이지와 GCMConstants 내 static variable 참조한다. */ } @Override protected void onMessage(Context arg0, Intent arg1) { // TODO Auto-generated method stub /** * GCMServer가 전송하는 메시지가 정상 처리 된 경우 구현하는 메소드이다. * Notification, 앱 실행 등등 개발자가 하고 싶은 로직을 해당 메소드에서 구현한다. * 전달받은 메시지는 Intent.getExtras().getString(key)를 통해 가져올 수 있다. */ } @Override protected void onRegistered(Context arg0, String regId) { // TODO Auto-generated method stub /** * GCMRegistrar.getRegistrationId(context)가 실행되어 registrationId를 발급받은 경우 해당 메소드가 콜백된다. * 메시지 발송을 위해 regId를 서버로 전송하도록 하자. */ } @Override protected void onUnregistered(Context arg0, String arg1) { // TODO Auto-generated method stub /** * GCMRegistrar.unregister(context) 호출로 해당 디바이스의 registrationId를 해지요청한 경우 해당 메소드가 콜백된다. */ } }

3. 공통 함수를 모아놓은 공통 유틸 클래스이다.

 구현하기 귀찮으면 상기 소스에서 직접 하단의 내용을 적용해도 무방하다.

package com.leminity.gcmsampleapp;

public class CommonUtils {
	
	
	/**
	 * 인자값이 null이거나 trim의 결과가 ""인 경우 true를 리턴한다.
	 * @param String
	 * @return boolean
	 */
	public static boolean isEmpty(String value){
		
		boolean isEmpty = false;
		
		if((value == null) || value == null)
			isEmpty = true;
		
		return isEmpty;
	}

}

4.상수 전용 클래스이다. 구현하기 귀찮으면 소스 내 상수를 적용해도 무방하다.

package com.leminity.gcmsampleapp;

public class Constants {
	
	public static final String PROJECT_ID="";//GCM으로부터 발급받은 PROJECT_ID

}
5.AndroidManifest.XML에 Receiver와 Service 및 Permission을 추가해야 한다.



    

    
        
            
                

                
            
        
    
    
	
	  
	    
	    
	    
	  
	
	
	
    
	
    
    
	
	
	
	
	
	 
	
	
	
	 


상기 내용을 구현한 샘플용 프로젝트를 첨부하니 참고가 되었으면 한다.


GCMSampleApp.zip