Android Google Cloud Message 설정

30
Google Cloud Message 2014.1
  • Upload

    -
  • Category

    Software

  • view

    1.504
  • download

    7

description

Android GCM 메세지 push 하는 셈플입니다.

Transcript of Android Google Cloud Message 설정

Page 1: Android Google Cloud Message 설정

Google Cloud Message2014.1

Page 2: Android Google Cloud Message 설정

Google Cloud Message for Android 스위치 활성화

Page 3: Android Google Cloud Message 설정

Google Cloud Message for Android 스위치 활성화

Page 4: Android Google Cloud Message 설정

3-rd-party 서버키 만들기

Page 5: Android Google Cloud Message 설정

3-rd-party 서버키 만들기

Page 6: Android Google Cloud Message 설정

3-rd-party 서버키 만들기

Page 7: Android Google Cloud Message 설정

3-rd-party 서버키 만들기

Page 8: Android Google Cloud Message 설정

API Project 번호 복사

Page 9: Android Google Cloud Message 설정

google-play-services_lib 프로젝트 import

Page 10: Android Google Cloud Message 설정

google-play-services_lib 프로젝트 import

Page 11: Android Google Cloud Message 설정

google-play-services_lib 프로젝트 import

Page 12: Android Google Cloud Message 설정

google-play-services_lib 프로젝트 import

android sdk 다운로드 폴더로 이동해서 google-play-services_lib 프로젝트를 선택해서 import 한다.

Page 13: Android Google Cloud Message 설정

프로젝트를 만들고 import 된 google-play-services_lib 프로젝트를 라이브러리로 참조하도록 설정한다.

Page 14: Android Google Cloud Message 설정

라이브러리 프로젝트 참조 설정

Page 15: Android Google Cloud Message 설정

AndroidManifest.xml 설정

<uses-permission android:name="android.permission.INTERNET" />!<uses-permission android:name="android.permission.GET_ACCOUNTS" />!<uses-permission android:name="android.permission.WAKE_LOCK" />!<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />!

!<permission android:name="com.example.day15gcm.permission.C2D_MESSAGE"!

android:protectionLevel="signature" />!<uses-permission android:name="com.example.day15gcm.permission.C2D_MESSAGE" />

위의 코드를 AndroidManifest.xml 에 <manifest></manifest> 의 자식요소로 붙여 넣는다.

<permission android:name="app 페키지명.permission.C2D_MESSAGE"! android:protectionLevel="signature" />!

<uses-permission android:name="app 페키지명.permission.C2D_MESSAGE" />

Page 16: Android Google Cloud Message 설정

AndroidManifest.xml 설정! <meta-data android:name="com.google.android.gms.version"!! ! android:value="@integer/google_play_services_version"/>!! <receiver!! ! android:name=".GcmBroadcastReceiver"!! ! android:permission="com.google.android.c2dm.permission.SEND" >!! ! <intent-filter>!! ! ! <action android:name="com.google.android.c2dm.intent.RECEIVE" />!! ! ! <category android:name="com.example.day15gcm" />!! ! </intent-filter>!! </receiver>!! <service android:name=".GcmIntentService" />

위의 코드를 AndroidManifest.xml 에 <application></application> 의 자식요소로 붙여 넣는다.

<category android:name="app 페키지명" />!

Page 17: Android Google Cloud Message 설정

MainActivity.java 코딩

! //필요한 상수 정의하기 ! public static final String EXTRA_MESSAGE = "message";! public static final String PROPERTY_REG_ID = "registration_id";! private static final String PROPERTY_APP_VERSION = "appVersion";! private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;!! //Google API Console 에서 만든 API Project Number! String SENDER_ID = "623534051417";!! static final String TAG = "GCMDemo";! GoogleCloudMessaging gcm;! SharedPreferences prefs;! Context context;! ! //Google Server 에서 발급받은 디바이스 아이디를 저장할 맴버필드 ! String regid;

위의 코드를 맴버필드로 붙여넣기

Page 18: Android Google Cloud Message 설정

MainActivity.java 코딩 @Override! public void onCreate(Bundle savedInstanceState) {! super.onCreate(savedInstanceState);! setContentView(R.layout.activity_main);! context=getApplicationContext();! //Google play Service 가 사용가능한 디바이스 인지 확인해서 ! if (checkPlayServices()) {//사용가능한 디바이스라면 ! ! //GoogleColoudMessageing 객체를 얻어온다. ! gcm = GoogleCloudMessaging.getInstance(this);! //디바이스 아이디를 읽어와 본다. ! regid = getRegistrationId(context);! Log.e("디바이스 아이디가 이미 발급되었습니다.", regid);! //만일 아직 발급받지 않은 상태라면 ! if (regid.isEmpty()) {! !//발급을 받는 메소드를 호출한다. ! registerInBackground();! }! } else {! Toast.makeText(this, ! !! "이 기기는 Google play Service 가 설치 되어있지 않습니다.",! !! 0).show();! }! }

onCreate() 메소드 작성

Page 19: Android Google Cloud Message 설정

MainActivity.java 코딩

//Google Play Service 가 사용 가능한지 체크해서 ! //사용가능하면 true, 사용 불가능하면 false 를 리턴하는 메소드 ! private boolean checkPlayServices() {! int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);! if (resultCode != ConnectionResult.SUCCESS) {! if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {! GooglePlayServicesUtil.getErrorDialog(resultCode, this,! PLAY_SERVICES_RESOLUTION_REQUEST).show();! } else {! Log.i(TAG, "This device is not supported.");! finish();! }! return false;! }! return true;! }

checkPlayServices() 메소드 작성

Page 20: Android Google Cloud Message 설정

//xml 문서에 디바이스 아이디가 저장되어 있는지 확인해서 리턴하는 메소드! //저장되어 있다면 저장된 디바아스 아이디가 리턴된다.! //저장되어 있지 않다면 빈 문자열 "" 이 리턴된다. ! 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 "";! }! //만일 앱의 버전이 바뀌었다면 빈문자열 "" 을 리턴해준다. ! 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;! }

MainActivity.java 코딩

Page 21: Android Google Cloud Message 설정

//SharedPreferences 객체를 리턴하는 메소드 ! private SharedPreferences getGCMPreferences(Context context) {! ! //MainActivity.xml 을 Access 하는 SharedPreferences 객체 리턴하기 ! return getSharedPreferences(MainActivity.class.getSimpleName(),! Context.MODE_PRIVATE);! }! //현재 App 의 버전을 리턴하는 메소드 ! private static int getAppVersion(Context context) {! try {! PackageInfo packageInfo = context.getPackageManager()! .getPackageInfo(context.getPackageName(), 0);! return packageInfo.versionCode;! } catch (NameNotFoundException e) {! throw new RuntimeException("Could not get package name: " + e);! }! }

MainActivity.java 코딩

Page 22: Android Google Cloud Message 설정

//메인 스레드가 아닌곳에서 디바이스를 등록하고 디바이스 아이디를 발급받는 메소드 ! private void registerInBackground() {! ! new RegistrationThread().start();! }! ! //현재 App의 버전과 디바이스 아이디를 xml 문서에 저장하는 메소드 ! private void storeRegistrationId(Context context, String regId) {! final SharedPreferences prefs = getGCMPreferences(context);! int appVersion = getAppVersion(context);! Log.i(TAG, "Saving regId on app version " + appVersion);! SharedPreferences.Editor editor = prefs.edit();! editor.putString(PROPERTY_REG_ID, regId);! editor.putInt(PROPERTY_APP_VERSION, appVersion);! editor.commit();! }! //3-rd-party Server 에 디바이스 아이디를 전송하는 메소드 ! public void sendRegistrationIdToBackend(){! ! //프로젝트 상황에 맞게 구현한다. ! ! ! }! @Override! protected void onResume() {! super.onResume();! checkPlayServices();! }

MainActivity.java 코딩

Page 23: Android Google Cloud Message 설정

class RegistrationThread extends Thread{! ! public void run(){! try {! if(gcm == null){! gcm = GoogleCloudMessaging.getInstance(context);! }! //Google Server 에 디바이스 아이디를 발급요청하고 ! //발급된 아이디를 맴버필드에 저장한다.! regid = gcm.register(SENDER_ID);! //로그에 발급된 아이디 출력하기! Log.e("디바이스 아이디가 발급되었습니다!", regid);! //디바이스 아이디를 3-rd-party 서버에 전송하는 메소드 호출! sendRegistrationIdToBackend();! //발급받은 디바이스 아이디를 xml 문서에 저장한다. ! storeRegistrationId(context, regid);! } catch (IOException ex) {//아이디 발급 실패! Log.e("아이디 발급중 에러발생!",ex.getMessage());! }! ! }! }

MainActivity.java 에 Inner Class 로 작성한다.

Page 24: Android Google Cloud Message 설정

GcmBroadcastReceiver.java 작성

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver{!!! @Override!! public void onReceive(Context context, Intent intent) {!! ! // Explicitly specify that GcmIntentService will handle the intent.! ComponentName comp = new ComponentName(context.getPackageName(),! GcmIntentService.class.getName());! // Start the service, keeping the device awake while it is launching.! startWakefulService(context, (intent.setComponent(comp)));! setResultCode(Activity.RESULT_OK);! !! }!}

Page 25: Android Google Cloud Message 설정

GcmIntentService.java 작성

public class GcmIntentService extends IntentService{!! ! public static final int NOTIFICATION_ID = 1;! private NotificationManager mNotificationManager;! NotificationCompat.Builder builder;!! !! public GcmIntentService() {!! ! super("GcmIntentService");!! ! !! }!!}!

Page 26: Android Google Cloud Message 설정

GcmIntentService.java 작성! @Override!! protected void onHandleIntent(Intent intent) {! Bundle extras = intent.getExtras();! GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);! //도착된 메세지 타입을 읽어온다. ! String messageType = gcm.getMessageType(intent);! ! if (!extras.isEmpty()) { ! 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());! } else if (GoogleCloudMessaging.! MESSAGE_TYPE_MESSAGE.equals(messageType)) {! !//Google Server 로 부터 받은 메세지! !String msg=extras.getString("msg");! ! !//알림 띄우는 메소드 호출 ! sendNotification(decodedMsg);! }! }! // Release the wake lock provided by the WakefulBroadcastReceiver.! GcmBroadcastReceiver.completeWakefulIntent(intent);! ! ! !! }

Page 27: Android Google Cloud Message 설정

GcmIntentService.java 작성

//전달 받은 메세지를 알림센터에 띄우는 메소드 ! private void sendNotification(String msg) {! mNotificationManager = (NotificationManager)! this.getSystemService(Context.NOTIFICATION_SERVICE);!! PendingIntent contentIntent = PendingIntent.getActivity(this, 0,! new Intent(this, MainActivity.class), 0);!! NotificationCompat.Builder mBuilder =! new NotificationCompat.Builder(this)! .setSmallIcon(R.drawable.ic_launcher)! .setContentTitle("GCM Notification")! .setStyle(new NotificationCompat.BigTextStyle()! .bigText(msg))! .setContentText(msg);!! mBuilder.setContentIntent(contentIntent);! mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());! }

Page 28: Android Google Cloud Message 설정

3rd-Party-Server 에 필요한 라이브러리 넣기

1. 안드로이드 sdk 설치된 폴더로 이동

sdk\extras\google\gcm\gcm-server\dist ! 2. gcm-server.jar 파일 복사 ! 3. 웹프로젝트의 Webcontent/WEB-INF/lib 폴더에 복사한 파일을 붙여 넣기한다.

Page 29: Android Google Cloud Message 설정

3rd-Party-Server 의 gcmTest.html<!DOCTYPE html>!<html>!<head>!<meta charset="UTF-8">!<title>gcmTest.html</title>!<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>!<script type="text/javascript">!! $(function(){!! ! $("#msg").keydown(function(event){!! ! ! if(event.which==13){!! ! ! ! send();!! ! ! }!! ! });!! });!! function send(){!! ! var msg=$("#msg").val();!! ! $.post("gcm.jsp",{"msg":msg},function(data){!! ! ! $("#msg").val("");!! ! });!! }!</script>!</head>!<body>!<input type="text" name="msg" id="msg"/>!<button onclick="send()">전송</button>!</body>!

Page 30: Android Google Cloud Message 설정

<%@page import="com.google.android.gcm.server.MulticastResult"%>!<%@page import="com.google.android.gcm.server.Message"%>!<%@page import="com.google.android.gcm.server.Sender"%>!<%@page import="java.util.ArrayList"%>!<%@page import="java.net.URLEncoder"%>!<%@ page pageEncoding="UTF-8"%>!<%!! request.setCharacterEncoding("utf-8");!! String clientId="안드로이드 디바이스 아이디";! !! String msg=request.getParameter("msg");!! String encodedMsg=URLEncoder.encode(msg, "utf-8");!! ArrayList<String> list=new ArrayList<String>();!! list.add(clientId);!! //전송자 객체 생성하면서 인자로 구글 프로젝트의 api key 값을 전달한다. !! Sender sender = new Sender("발급받은 api key");!! //메세지 빌더 객체를 생성한후 !! Message.Builder builder=new Message.Builder();!! //key : value 형태로 데이터를 담는다. !! builder.addData("msg", encodedMsg);!! //메세지 빌더객체를 이용해서 Message 객체를 얻어온다. !! Message message = builder.build();!! //전송자 객체를 이용해서 메세지를 전송한다. send(메세지, 받을사람, 재전송 시도 횟수) !! MulticastResult result = sender.send(message, list, 5); !%>

3rd-Party-Server 의 gcm.jsp