Android/Firebase(FCM)

안드로이드 - Firebase(FCM) 푸시알림 구현하기(2) (코틀린)

와구와구! 2020. 10. 29. 17:34

2. 푸시알림 예제 구현하기(토큰받기)

프로젝트와 파이어베이스를 연결하신후 진행해주시기 바랍니다.

아래 링크 참고해주세요.

 

jh3786.tistory.com/2

 

안드로이드 - Firebase(FCM) 푸시알림 구현하기(1)

1. 안드로이드 프로젝트와 파이어베이스 연결하기 안드로이드 프로젝트를 만들고 Firebase를 추가합니다. Firebase콘솔 : httpsL//console.firebase.google.com 프로젝트를 하나 만들어야 합니다  + 프로젝트

jh3786.tistory.com

 

FCM예제를 다루기 전에 먼저 AndroidManifest.xml에서

 

<service android:name=".MyFireBaseMessagingService">
	<intent-filter>
		<action android:name="com.google.firebase.MESSAGING_EVENT" />
	</intent-filter>
</service>

 

인터넷 권한 설정도 해줍니다.

 

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

 

MainActivity에 소스를 추가 합니다.

 FirebaseInstanceId.getInstance().instanceId
            .addOnCompleteListener(OnCompleteListener { task ->
                if (!task.isSuccessful) {
                    Log.w("FCM Log", "getInstanceId failed", task.exception)
                    return@OnCompleteListener
                }
                val token = task.result!!.token
                Log.d("FCM Log", "FCM 토큰: $token")
                Toast.makeText(this@MainActivity, token, Toast.LENGTH_SHORT).show()
 })

메인액티비티에서 토큰을 받아옵니다. (코틀린으로 작성되었습니다.)

 

3. 푸시알림 예제 구현하기(메시지 처리)

메시지를 수신하려면 FirebaseMessagingService를 확장하는 서비스를 사용합니다. 서비스에서 onMessageReceived  onDeletedMessages 콜백을 재정의해야 합니다.

 

메시지처리에 대한 자세한 내용은 다음에 포스팅 하겠습니다.

 

빠른 예제를 구현하기위해 다음으로 넘어가겠습니다.

MyFireBaseMessagingService.java 하나 만들어주세요

 

다음 소스를 추가해주세요.


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 androidx.core.app.NotificationCompat;

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


//onMessageReceived : 받은 메시지에서 title과 body를 추출

public class MyFireBaseMessagingService 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());
            String messageBody = remoteMessage.getNotification().getBody();
            String messageTitle = remoteMessage.getNotification().getTitle();
            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 notificationBuilder =
                    new NotificationCompat.Builder(this, channelId)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(messageTitle)
                            .setContentText(messageBody)
                            .setAutoCancel(true)
                            .setSound(defaultSoundUri)
                            .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, notificationBuilder.build());
        }
    }
}

소스를 추가 하셨다면 다시 Firebase 콘솔로 가셔서

여기서 메시지를 보내기시면 테스트 푸시알람을 받으실수 있습니다.!!!!

반응형