티스토리 뷰

프로젝트 진행중에 모델을 기다리는 시간동안 구현할 기능을 찾던 도중 푸시알림과 웹크롤링이 떠올랐다.

그 중 먼저 푸시알림을 구현하고자 열심히 구글과 유튜브를 돌아다녔다.

 

일단 FCM을 구현하기 위해서는 안드로이드 스튜디오에서 지원하는 Tools 바의 Firebase 연동이 필요하다

나는 구글 로그인 연동을 위하여 미리 준비가 되어있었다.

해당 내용은 검색을 해보면 자료가 많고 Firebase에 들어가도 가이드 형식으로 친절하게 나와있다.

 

Firebase 프로젝트를 생성하고 앱과 연결을 진행하였다면 FCM을 사용하기 위해서 

Tools -> Firebase에서 추가적으로 Cloud Messaging을 클릭하여

 

add FCM to your app를 클릭한다.

해당 과정을 진행하면 gradle에 자동적으로 

classpath 'com.google.gms:google-services:4.3.10'

이 생성되는데 오류를 해결하기 위해서 버전을 다운그레이드 하면 FCM이 해제되는걸 보아 최신 버전이 필수적인 것 같다.

 

이후 추가적으로 몇가지 코드를 작성해야 한다

 

manifests

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

name 은 FCM을 위하여 만든 자바파일의 이름을 쓰면 된다

 

gradle (app)

implementation 'com.google.firebase:firebase-messaging:23.0.5'
implementation 'com.google.firebase:firebase-analytics:21.0.0'

gradle(project)

buildscript {
    repositories {
        google()
        jcenter()
        maven{url 'https://jitpack.io'}
    }
    dependencies {
        classpath 'com.google.gms:google-services:4.3.10'
    }
    allprojects {
        // ...

        repositories {
            // Check that you have the following line (if not, add it):
            google()  // Google's Maven repository
            // ...
        }
    }
}

여기서 google()이 써있는 부분들이 필수적이다

 

이제 FCM을 위한 token을 가져오고 기능을 구현 할 Java 파일을 하나 생성한다

 

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.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

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

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        System.out.println("From: " + remoteMessage.getFrom());

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            System.out.println("Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
        sendNotification(remoteMessage.getFrom(), remoteMessage.getNotification().getBody());
        sendNotification(remoteMessage.getNotification().getBody());
    }

    private void sendNotification(String from, String body) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(MyFirebaseMessagingService.this.getApplicationContext(), from + " -> " + body,Toast.LENGTH_SHORT).show();
            }
        });
    }

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

        String channelId = "My channel ID";
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.logo)
                        .setContentTitle("My new notification")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

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

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

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

 해당 java 소스를 구현할 때 오류가 많이 발생했었다.

찾아 본 사이트마다 코드가 조금씩 다르고 이전 버전에서 지원하던 내용이

현재는 서비스 중지가 되었기 때문에 구글에서는 찾지 못하고 유튜브를 뒤진 결과 찾아왔다.

 

 

이후 MainActivity.java 파일에

 

        Intent intent = getIntent();
        if(intent != null) {//푸시알림을 선택해서 실행한것이 아닌경우 예외처리
            String notificationData = intent.getStringExtra("test");
            if(notificationData != null)
                Log.d("FCM_TEST", notificationData);
        }

        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(@NonNull Task<String> task) {
                        if (!task.isSuccessful()) {
                            System.out.println("Fetching FCM registration token failed");
                            return;
                        }

                        // Get new FCM registration token
                        String token = task.getResult();

                        // Log and toast
//                        System.out.println(token);
//                        Toast.makeText(LoginActivity.this, "Your device registration token is" + token
//                                , Toast.LENGTH_SHORT).show();
                    }
                });

해당 코드를 작성한다. 여기서도 위와 같은 오류가 참 많이 발생했는데 

 

FirebaseMessaging를 사용하지 않고 

다른 클래스를 사용하는 자료들이 많았는데 해당 클래스가 서비스 중지가 된것이었다.

 

여기까지 진행을 하고 오류가 뜨지 않았다면 푸시알람을 보낼 준비가 완료되었다.

 

이제 Firebase 사이트의 콘솔로 이동하여 

참여 파트에 있는 Cloud Messaging으로 이동하여 

 

send your first message를 클릭한다

 

제목과 텍스트를 입력하면 

우측의 테스트 메시지 발송이 있는데 

여기서 FCM 토큰을 추가해주어야 한다

 

토큰은 이미 코드에 토큰을 받아올 수 있도록 구현이 되어있기 때문에

앱을 구동하고 Log를 올려보면 토큰 형식으로 되어있는 Log를 발견할 수 있다

이걸 복사하여 토큰을 추가 -> 선택하여 테스트를 진행하면 성공적으로 푸시알람이 보내지는걸 확인할 수 있다!

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함