안녕하세요 오늘은 GCM 을 정리하려다 GCM 사이트를 들어가보니 FCM을 추천을 하고있어서
FCM으로 Android Push Message를 해보려고 합니다.
Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.
https://firebase.google.com/docs/cloud-messaging/android/client
예제로 제공되는 프르젝트 입니다.
https://github.com/firebase/quickstart-android/tree/master/messaging
<사전작업> https://console.firebase.google.com/?hl=ko
프로젝트를 생성하시고

새프로젝트 만들기 선택후 Android package name 부분에는 (패키지 이름은 보통 앱 수준 build.gradle 파일의 applicationId 입니다.)
저의 경우는 com.example.john.fcmtest 입니다.
|
전체적인 구성도는 아래와같습니다.

휴대폰에서 FCM 토큰을 생성하여 개인 서버로 전송을 합니다.
그리고 개인서버에는 그 토큰이 저장이 되어있고,
그뒤에 관리자가 push메시지를 보내야할때 서버에 저장이 되어있는 토큰을 이용하여
FCM 쪽으로 푸시요청을 합니다.
그럼 FCM 에서 해당토큰의 단말로 푸시메시지를 보냅니다.
사이트는 깔끔하고 한글화 도 잘되어있네요.
우선 프로젝트를 생성합니다.
한동안 android app을 안했는데 이제 분위기가
eclipse plugin 은 안쓰는 분위기고 Android Studio 를 사용하고 bulid 툴로는 gradle을 기본적으로 쓰는 가이드가 나오기때문에
저도 안드로이드 개발할때는 eclipse 를 안쓰고 Android Studio를 사용하도록 할예정입니다.
우선 프로젝트를 만들었습니다.
처음으로 할일은 project gradle에 classpath를 추가합니다.
그리고 run 을 누릅니다.
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
run 을 수행하면 콘솔창에 아래처럼 빌드 잘되었다고 뜹니다.
BUILD SUCCESSFUL
Total time: 7.069 secs
Process finished with exit code 0
그런뒤 app bulid.gradle에 추가를 합니다.
마찬가리로 run을 눌러 success 가 되는것을 확인한뒤 manifest.xml에 service를등록합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.john.fcmtest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
위에 코드처럼 <application> 태그 사이에 <service 부분을 넣습니다.
그리고 서비스를 만들어야겠죠?
class 를 추가합니다. 두가지 클래스를 만듭니다.
MyFirebaseMessagingService, MyFirebaseInstanceIDService를 생성하여 extends 합니다.
FirebaseMessagingService 와 FirebaseInstanceIdService 를 extends 합니다.
package com.example.john.fcmtest;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
* Created by John on 2017-04-08.
*/
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService
{
String TAG = "AAAAA";
String strUrl;
String result;
@Override
public void onTokenRefresh() {
Log.d(TAG, "bbb" );
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("uid", "aa")
.add("id", token)
.build();
//request
Request request = new Request.Builder()
.url("http://서버/register.do")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void onTokenRefresh() 는 단말접속을 하고 KCM 토큰이 생성되어있지않거나 리프레쉬될때 호출됩니다.
테스트 하실때는 앱을 삭제후 다시 설치하는 식으로 테스트하시기바랍니다.
package com.example.john.fcmtest;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
/**
* Created by John on 2017-04-08.
*/
public class MyFirebaseMessagingService extends FirebaseMessagingService
{
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification( remoteMessage.getData().get("msg"));
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_menu_camera)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
여기까지만 하시면 완료되셨습니다.

그뒤에 앱을 실행시키고 로그에 찍히는 토큰을 저장해두었다가.
크롬 클라이언트 프로그램중에 postman을 이용하여 호출을 해봅니다.
header 부분에도 FCM에 요청하신부분을 채워넣습니다.
https://firebase.google.com/docs/cloud-messaging/send-message?hl=ko
to 뒷부분에 값으로 앱실행했을때 토큰값을 입력하시면됩니다.
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

key=등록된 서버 키
https://console.firebase.google.com/project/testaaa-ad72b/settings/cloudmessaging?hl=ko
에서 만들어둔 프로젝트의 서버 정보를 입력하시면됩니다.
클라우드 메시징 탭을 클릭하시면 서버키 부분이있습니다.


앱을 실행후 해당 메시지를 보내면 application부분에 보입니다.

잘못된점이나 문의사항있으시면 말씀해주세요~