15. 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" />
16. 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 페키지명" />!
17. 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;
위의 코드를 맴버필드로 붙여넣기
18. 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() 메소드 작성
19. 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() 메소드 작성
20. //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 코딩
21. //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 코딩
22. //메인 스레드가 아닌곳에서 디바이스를 등록하고 디바이스 아이디를 발급받는 메소드 !
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 코딩
23. 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 로 작성한다.
24. 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);! !
! }!
}
25. GcmIntentService.java 작성
public class GcmIntentService extends IntentService{!
! !
public static final int NOTIFICATION_ID = 1;!
private NotificationManager mNotificationManager;!
NotificationCompat.Builder builder;!
! !
! public GcmIntentService() {!
! ! super("GcmIntentService");!
! ! !
! }!
!
}!
26. 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);!! ! !
! }
28. 3rd-Party-Server 에 필요한 라이브러리 넣기
1. 안드로이드 sdk 설치된 폴더로 이동
sdkextrasgooglegcmgcm-serverdist
!
2. gcm-server.jar 파일 복사
!
3. 웹프로젝트의 Webcontent/WEB-INF/lib
폴더에 복사한 파일을 붙여 넣기한다.