본문 바로가기
클라우드 아키텍처 설계 기초지식/12 AWS

AWS - GCM (Google Cloud Messege)

by Jasie 2018. 11. 24.



GCM


Google Cloud Messege는 클라우드서버로 부터 PUSH 서비스를 받기 위해서는 구글에서 제공하는서비스를 이용해야 한다. 




(1)안드로이드 스튜디오 기본 설치


안드로이드 기기가 없는자는 https://console.firebase.google.com/?hl=ko에서 안드로이드 스튜디오 설치를 한다.


 




(2) Firebase에서 앱 등록




Firebase 콘솔에서 안드로이드 모양 클릭


Android 패키지 이름 : com.sjb.push

안드로이드 스튜디오에서 Application Name, Company Domain을 뒤에서부터 소문자로 반대로 써준다.

앱 닉네임(선택사항) : 마음대로


앱 등록 클릭


google-services.json 파일 다운


google-services.json 파일을 안드로이드 스튜디오의 프로젝트의 app 밑에 복사


프로젝트 안의 build.gradle 파일 수정

    dependencies {

        classpath 'com.android.tools.build:gradle:3.2.1'


        classpath 'com.google.gms:google-services:4.0.1' //얘를 추가한다.

        // NOTE: Do not place your application dependencies here; they belong

        // in the individual module build.gradle files

    }


프로젝트 안의 app 폴더 안의 build.gradle 파일 수정

  dependencies {

      implementation fileTree(dir: 'libs', include: ['*.jar'])

      implementation 'com.android.support:appcompat-v7:28.0.0'

      implementation 'com.android.support:support-media-compat:28.0.0' // 얘 추가

      implementation 'com.android.support:animated-vector-drawable:28.0.0' // 얘 추가

      implementation  'com.android.support:support-v4:28.0.0' // 얘 추가

      implementation 'com.android.support.constraint:constraint-layout:1.1.3'

      implementation 'com.google.firebase:firebase-core:16.0.4' // 얘 추가

      implementation 'com.google.firebase:firebase-messaging:17.3.4' // 얘 추가

      testImplementation 'junit:junit:4.12'

      androidTestImplementation 'com.android.support.test:runner:1.0.2'

      androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

  }

  apply plugin: 'com.google.gms.google-services' // 얘 추가


안드로이드 스튜디오의 오른쪽 위에 sync now를 클릭


Firebase 콘솔에서 다음 누르고 통과되던가 아니면 그냥 이 단계 건너뛰기


  (3) 안드로이드 스튜디오에서 클래스 생성



app/src/main/java/[패키지]/MyFirebaseMessagingService




package com.sjb.push;


import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

import android.graphics.BitmapFactory;

import android.media.RingtoneManager;

import android.net.Uri;

import android.support.v4.app.NotificationCompat;

import android.util.Log;


import com.google.firebase.messaging.RemoteMessage;


import java.util.Map;


public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();


    // 메시지 수신

    @Override

    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.i(TAG, "onMessageReceived");


        Map<String, String> data = remoteMessage.getData();

        String title = data.get("title");

        String message = data.get("message");


        sendNotification(title, message);

    }


    private void sendNotification(String title, String message) {

        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_CANCEL_CURRENT);


        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)

            .setLargeIcon(BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_dialog_info))

            .setSmallIcon(R.mipmap.ic_launcher)

            .setContentTitle(title)

            .setContentText(message)

            .setAutoCancel(true)

            .setSound(defaultSoundUri)

            .setContentIntent(pendingIntent);


        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

    }

}



app/src/main/java/[패키지]/MyFirebaseInstanceIDService



package com.sjb.push;


import android.util.Log;


import com.google.firebase.iid.FirebaseInstanceId;

import com.google.firebase.iid.FirebaseInstanceIdService;


public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();


    // 토큰 재생성

    @Override

    public void onTokenRefresh() {

        // Get updated InstanceID token.

        String token = FirebaseInstanceId.getInstance().getToken();

    Log.d(TAG, "token = " + token);

    }

}




  (4) app/src/main/java/[패키지]/MainActivity 수정



package com.sjb.push


import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.text.TextUtils;

import android.util.Log;


import com.google.firebase.iid.FirebaseInstanceId;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        FirebaseInstanceId.getInstance().getToken();


        if (FirebaseInstanceId.getInstance().getToken() != null) {

            Log.d(TAG, "token = " + FirebaseInstanceId.getInstance().getToken());

        }

    }

}




  (5) app/src/main/AndroidManifest.xml 수정



</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>




<uses-permission android:name="android.permission.INTERNET"/>


  <application   //이거 위에 uses-permission 추가



  (6) 안드로이드 가상머신 설치

안드로이드 스튜디오의 상단 메뉴 중 Tools -> AVD Manager -> Create Virtual Device -> Pixel 선택 -> Nougat Download 클릭

-> next -> Finish


  (7) 실행

안드로이드 스튜디오에서 위에 초록색 실행 버튼 클릭으로 실행


  (8) 테스트1 (앱을 설치한 모든 핸드폰에 보내기)

Firebase 콘솔에서 왼쪽에 성장 -> Cloud Messaging  -> Send Your First Message -> 메시지 제목 : test -> 다음 -> 앱 : [본인 앱] -> 게시

       메시지 내용 : qwer


  (9) 테스트2 (특정 핸드폰에 보내기)


curl -X POST -H "Authorization: key=[서버키]" -H "Content-Type: application/json" -d '{

    "to": "[토큰]",

    "data": {

        "title":"My Push Test",

        "message":"Test Message"

    }

}'  https://fcm.googleapis.com/fcm/send



[서버키] : Firebase 콘솔에서 -> Project Overview 옆 톱니바퀴 -> 프로젝트 설정 -> 클라우드 메시징 -> 서버키 복사

[토큰] : 안드로이드 스튜디오에서 밑에 Logcat에서 token 검색 -> 어플을 실행 했을 때 token이 로그에 찍혀 나옴



*안되면 Firebase 콘솔에서 앱을 지웠다가 다시 생성



3. AWS SNS


AWS (SNS)서비스


애플리케이션 -> 플랫폼 애플리케이션 생성 -> 이름 : test -> 생성

      플랫폼 : GCM

      API 키 : [서버 키]


애플리케이션 체크 -> 플랫폼 엔드포인트 생성 -> 디바이스 토큰 : [토큰] ->엔드포인트 추가

사용자 데이터 : 비워둔채로


애플리케이션의 ARN을 클릭 -> 엔드포인트 체크 후 -> 엔드포인트에 게시 -> JSON 체크 내용을 다음처럼 입력


{

"GCM": "{ \"data\": {\"title\": \"[제목]\" , \"message\": \"[내용]\" } }"

}



공감() 과 댓글은 필자에게 큰 힘이 됩니다.

잠시 1초만 내주시면 안될까요? ~~


로그인 없이도 가능합니당 



'클라우드 아키텍처 설계 기초지식 > 12 AWS' 카테고리의 다른 글

AWS - VPC  (0) 2018.11.21
AWS - Glacier  (0) 2018.11.21
AWS - 오토스케일링 생성 실습  (0) 2018.11.21
AWS (4) - RDS,mysql,웹연동  (0) 2018.11.19
ASW (3) - 우분투 방화벽  (0) 2018.11.16

댓글