2016년 4월 10일 일요일

GCM 5. GcmListenerService

GCM으로 메시지가 도착했을때 액션을 정의

- onMessageReceived() : GCM으로부터 이 함수를 통해 메세지를 받는다.
이때 전송한 SenderID와 Set 타입의 데이터 컬렉션 형태로 받음

- sendNotification() : GCM으로부터 받은 메세지를 디바이스에 알려주는 함수

package com.example.rock.opregcheck;

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.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

/**
 * Created by rock on 2016-04-05.
 */
public class GcmListenerService extends com.google.android.gms.gcm.GcmListenerService {
    static final String TAG = "GcmListenerService";

    @Override
    public void onMessageReceived(String from, Bundle data) {
        //super.onMessageReceived(from, data);

        String title = data.getString("title");
        String message = data.getString("message");

        Log.d(TAG, "From: " + from);
        Log.d(TAG, "data: " + data);
        Log.d(TAG, "Title: " + title);
        Log.d(TAG, "Message: " + message);

        sendNotification(title, message);
    }

    /**
     * 실제 디바에스에 GCM으로부터 받은 메세지를 알려주는 함수이다. 
     * 디바이스 Notification Center에 나타난다.
     * @param title
     * @param 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, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.korea)
                .setTicker("GCM 에서 메시지가 도착하였습니다.")
                .setWhen(System.currentTimeMillis())
                .setNumber(10)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

        notificationManager.notify(0, notificationBuilder.build());
    }
}

댓글 없음 :

댓글 쓰기