GCM을 새 프로젝트에 추가해야 하는데, 2년 만에 많이 변경됐다.
기존에는 수동으로 해야하던 것들이 이젠 구글이 만들어 주는 것들이 많다.
일단 https://developers.google.com/cloud-messaging/android/start 으로 간다.
google-services.json 받기
Get a configuration file 을 클릭해서 https://developers.google.com/mobile/add?platform=android&cntapi=gcm&cntapp=Default%20Demo%20App&cntpkg=gcm.play.android.samples.com.gcmquickstart&cnturl=https:%2F%2Fdevelopers.google.com%2Fcloud-messaging%2Fandroid%2Fstart%3Fconfigured%3Dtrue&cntlbl=Continue%20with%20Try%20Cloud%20Messaging 로 이동한다.
이런 화면이 뜨는데,
- App name에는 새 프로젝트의 이름이나 기존 프로젝트의 이름을 넣는다. 다 지우면 기존 프로젝트 목록이 뜬다. 혹은 기존 프로젝트 목록 https://console.developers.google.com/project 에서 앱 이름을 가져온다.
- Android package name은 작업할 앱의 패키지 경로를 넣는다.
- Your country/region 은 대한민국을 선택한다.
Choose and configure services
가운데의 Enable google cloud messaging을 클릭하면
이런 화면으로 변경되고, 아래쪽에 활성화 된 Generate configuration files 버튼을 클릭한다.
Download and install configuration
Downlaod google-services.json 을 클릭해서 파일을 다운 받는다.
{ "project_info": { "project_id": "crucial-ray-456", "project_number": "939290888005", "name": "TestGCM2" }, "client": [ { "client_info": { "mobilesdk_app_id": "1:939290888005:android:1a5d395909015ec1", "client_id": "android:kr.susemi99.gcm", "client_type": 1, "android_client_info": { "package_name": "kr.susemi99.gcm" } }, "oauth_client": [], "api_key": [], "services": { "analytics_service": { "status": 1 }, "cloud_messaging_service": { "status": 2, "apns_config": [] }, "appinvite_service": { "status": 1, "other_platform_oauth_client": [] }, "google_signin_service": { "status": 1 }, "ads_service": { "status": 1 } } } ], "client_info": [], "ARTIFACT_VERSION": "1" }
파일 내용은 위와 같다.
GCM 전송용 key 받기
https://console.developers.google.com/project – 아까 만든 프로젝트 – API 관리자 – 사용자 인증 정보 – Server Key 의 key 를 가져오면 된다.
(아마 아까 google-services.json 만들면서 자동으로 만들어져 있을 것이다.)
전송할 때 필요하니 복사해놓자.
샘플 코드
https://github.com/googlesamples/google-services.git 에 샘플 코드가 있다.
안드로이드용 GCM 코드는 https://github.com/googlesamples/google-services/tree/master/android/gcm 에 있다.
패지키 경로를 아까 생성할 때 사용한 kr.susemi99.gcm 으로 새로운 프로젝트를 만든다.
- build.gradle 세팅 & google-services.josn 복사하기
- MainActivity 수정하기
- Registration 후 token 받기
- 서버로 token 보내기 함수 추가
- GCM 메시지 받기
- Notification 보내기
- Token 변경 시 다시 서버로 보내기 및 추가 작업
GCM 전송 데모
https://gcmsender.herokuapp.com 에서 데모로 전송해보고 오류가 있는지 확인한다.
코드 : https://github.com/susemi99/GCM-client-sample2