본문 바로가기
Android

FCM(Firebase Cloud Messaging) 메세지 받기

by 캡틴노랑이 2020. 9. 29.
반응형

FCM에 대해서 자세한 설명은 생략.
이미 어느정도 이해하고 왔을 것으로 판단됨. 
소스만 고대로 올려 놓음. 
마시멜로우 기준으로 코딩. 그 이외 버전에서는 작동 안될 수 있음. 

 

MainActivity

package com.norang.firebasesample;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;

public class MainActivity extends AppCompatActivity {

    private TextView tvToken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvToken = findViewById(R.id.tvToken);

        FirebaseInstanceId.getInstance().getInstanceId()
        .addOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete(@NonNull Task task) {
                if (!task.isSuccessful()) {
                    Log.w("FCM", "getInstanceId failed", task.getException());
                    return;
                }
                String token = task.getResult().getToken();
                Log.d("Token", token);
                tvToken.setText(token);
            }
        });
    }
}

MainActivity Layout

 

FirebaseMessagingService

package com.norang.firebasesample;


import android.app.Notification;
import android.app.NotificationChannel;
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.Build;
import android.util.Log;
import android.graphics.Color;

import androidx.core.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class NorangFireBaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onNewToken(String token) {
        Log.d("FCM Log", "Refreshed token: " + token);
    }
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getNotification() != null) {
            Log.d("FCM Log", "알림 메시지: " + remoteMessage.getNotification().getBody());

            Log.d("FCM Log data", "알림 메시지: " + remoteMessage.getData().get("data1"));
            Log.d("FCM Log data", "알림 메시지: " + remoteMessage.getData().get("data2"));
            Log.d("FCM Log data", "알림 메시지: " + remoteMessage.getData().get("data3"));


            //일반 메세지
            String messageTitle = remoteMessage.getNotification().getTitle();
            String messageBody = remoteMessage.getNotification().getBody();

            //data 영역 읽어오기
//            String messageTitle = remoteMessage.getData().get("data2");
//            String messageBody = remoteMessage.getData().get("data1");


            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);
            String channelId = "Channel ID";

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            
            NotificationCompat.Builder nBuilder =
                    new NotificationCompat.Builder(this, channelId)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(messageTitle)
                            .setContentText(messageBody)
                            .setAutoCancel(true)
                            .setSound(defaultSoundUri)
                            //.setColor(Color.YELLOW)  //아이콘 배경에 색상이 들어감
                            .setLights(Color.YELLOW, 1000, 1000)/// 1초 간격으로 깜빡임.  이것도 되다 안되다 함. 젠장할...
                            .setContentIntent(pendingIntent);

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

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String channelName = "Channel Name";
                NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
                notificationManager.createNotificationChannel(channel);
            }
            notificationManager.notify(0, nBuilder.build());
        }
    }
}

AndroidManifest

 

반응형

'Android' 카테고리의 다른 글

자주 쓰는 코드 모음.  (4) 2020.10.30
Timer  (3) 2020.10.14
안드로이드 개발시 쓰는 log  (2) 2020.09.03
runOnUiThread  (1) 2020.08.18
안드로이드 버전  (2) 2020.08.18

댓글