반응형



1. 단말기의 메인 액티비티에 정의해주어야 할 부분.

	/**
	 * GCM 서비스를 받기 위해 등록
	 */
	public void getGCMRegId() {
		String PROJECT_ID = "313252642651";
		
		Log.d("HSE_LOG", "단말기 ID를 등록합니다.");
		
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		final String MobileDeviceID = GCMRegistrar.getRegistrationId(this);
		if ("".equals(MobileDeviceID)) {
			GCMRegistrar.register(this, PROJECT_ID);
		} 
		else {
			// 이미 GCM 을 사용하기위해 등록ID를 구해왔음
			Log.v("HSE_LOG", "Already REGISTERED");
			GCMRegistrar.unregister(this);
			GCMRegistrar.register(this, PROJECT_ID);
		}
	}



2. 1번을 사용하기 위한 GCMIntentService.java 정의

 
 이 자바 파일은 GCM의 핵심으로서 매니페스트 파일에 기본 패키지에 들어가 있어야한다.


public class GCMIntentService extends GCMBaseIntentService { NotificationManager notiManager; String nNARID = ""; String nAcciRepID = ""; String nImvMesurType = ""; private static final String PROJECT_ID = "313252642651"; // 구글 api 페이지 주소 [https://code.google.com/apis/console/#project:긴 번호] // #project: 이후의 숫자가 위의 PROJECT_ID 값에 해당한다 // public 기본 생성자를 무조건 만들어야 한다. public GCMIntentService() { this(PROJECT_ID); } public GCMIntentService(String project_id) { super(project_id); } /** 푸시로 받은 메시지 */ /* push가 들어왔을때 실행되는 함수 */ protected void onMessage(Context pContext, Intent arg1) { notiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Log.d("HSE_LOG", "New Message = "); if (arg1.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) { Log.d("HSE_LOG", "onMesaage"); nNARID = arg1.getExtras().getString("NearAccidentReportID"); nAcciRepID = arg1.getExtras().getString("AccidentDescription"); nImvMesurType = arg1.getExtras().getString("ImprovementMeasuresType"); Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(500); showMessage(); } } public void showMessage() { Thread thread = new Thread(new Runnable() { public void run() { handler.sendEmptyMessage(0); } }); thread.start(); } protected void on_error(Context context, String errorId) { Log.d("HSE_LOG", "on_error. errorId : " + errorId); } /** 단말에서 GCM 서비스 등록 했을 때 등록 id를 받는다 */ protected void onRegistered(Context context, String regId) { Log.d("HSE_LOG", "onRegistered. regId : " + regId); } /** 단말에서 GCM 서비스 등록 해지를 하면 해지된 등록 id를 받는다 */ protected void onUnregistered(Context context, String regId) { Log.d("HSE_LOG", "onUnregistered. regId : " + regId); } /** 에러 발생시 */ protected void onError(Context context, String errorId) { Log.d("HSE_LOG", "on_error. errorId : " + errorId); } /** * 메시지 도착시 알림을 수행할 메소드 */ private Handler handler = new Handler() { public void handleMessage(Message msg) { Notification noti = new Notification(R.drawable.ic_launcher, "HSE 메시지 도착!", System.currentTimeMillis()); noti.flags = Notification.FLAG_ONLY_ALERT_ONCE; // 기본으로 지정된 소리를 내기 위해 noti.defaults = Notification.DEFAULT_SOUND; // 알림 소리를 한번만 내도록 noti.flags = Notification.FLAG_ONLY_ALERT_ONCE; // 확인하면 자동으로 알림이 제거 되도록 noti.flags = Notification.FLAG_AUTO_CANCEL; // 사용자가 알람을 확인하고 클릭했을때 새로운 액티비티를 시작할 인텐트 객체 Intent intent = new Intent(GCMIntentService.this, LoginActivity.class); intent.putExtra("reportNum", ""); intent.setData(Uri.parse(nNARID)); Log.d("HSE_LOG", "GCMMESSAGE : " + nNARID); // 새로운 태스크(Task) 상에서 실행되도록(보통은 태스크1에 쌓이지만 태스크2를 만들어서 전혀 다른 실행으로 관리한다) // intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // 인텐트 객체를 포장해서 전달할 인텐트 전달자 객체 PendingIntent pendingI = PendingIntent.getActivity(GCMIntentService.this, 0, intent, 0); noti.setLatestEventInfo(GCMIntentService.this, "메시지가 도착하였습니다!", "[" + nAcciRepID + "]" + nImvMesurType, pendingI); // 알림창 띄우기(알림이 여러개일수도 있으니 알림을 구별할 상수값, 여러개라면 상수값을 달리 줘야 한다.) notiManager.notify(0, noti); Context context = getApplicationContext(); Toast toast = Toast.makeText(context, nNARID, Toast.LENGTH_SHORT); toast.show(); Log.i("HSE_LOG", "gcmNum : " + nNARID); Log.i("HSE_LOG", "MSG : " + msg.toString()); nNARID = null; nAcciRepID = null; nImvMesurType = null; } }; }


3. 헛갈리지 말아야 할 것과 용어 정리.

 첫째. GCMIntentService에서 on~~하는 메소드들은 GCM 라이브러리를 통해 연산되는 것을 알아채고

        그에 관련 된 것들이 실행이 될 때에 "야, 지금 이런 메소드와 관련된 연산이 일어났는데 어쩔꺼야?"하고 물었을 때

        "그건 이렇게 하면 되!" 라고 알려주는 것이다.

 둘째. Key for browser apps API Key는 구글의 GCM 기능을 얻어오는 것이다. 즉, 단순히 내가 이용할 수 있는 허용권을 얻은 것이다.

        그래서 이 키를 이용하면 서버에서 단말기로 메세지를 보낼 수 있는 것이다.

 셋째. 푸시란, 서버에서 단말기에 메시지를 뿌리는 행위를 말한다. 즉, 받은 메시지를 단말기 ID에 맞게 뿌려주는 것이다.

 넷째. Project Key는 둘째에서 말한 것과 반대의 역활이다. 단말기에서 서버에 단말기 ID를 저장할 때 필요한 것이다.

 다섯. 단말기 ID란 1.에서 했던 행위로 얻어지는 앱+디바이스 로 이루어진 고유의 키를 말한다.


 정리하자면, A라는 사람이 B라는 사람의 단말기로 메세지를 보내고 싶을 때 이용하는 것이 바로 GCM인데,

여기서 A라는 사람은 GCM에 접근하기 위한 API Key를 이용해 메세지를 보내야(푸시)한다. 그런데 주소를 알아야

보내지 않겠는가? 그래서 A는 B에게 자신의 Project Key를 주고, B는 자신의 단말기와 앱의 ID를 결합시켜(onRegistered)진 

주소(아이디)를 A에게 보내주고 A는 받은 주소로 GCM을 이용해 디바이스 ID 주소로 메시지를 보내는 것이다.


 즉, GCM은 우체국의 개념이고, API Key는 개인이 사용하는 우체통, Project Key는 개인이 사용하는 우체통에서 받을 수 있는 사람을

의미하고, Project Key를 이용해 만들어진 RegID는 받는이의 주소가 된다.

반응형

WRITTEN BY
데르벨준

,