본문으로 건너뛰기

cloud-messaging

FirebaseCloudMessaging (푸시 알림) in Android Studio

이 글은 기존 블로그의 원문에서 가져왔습니다. 원문 작성일: 2021-08-16

Firebase Cloud Messaging 참고 영상 (YouTube)

Firebase Cloud Messaging을 활용해서 앱이 깔려있는 디바이스에 알람을 보내거나 할 수 있다.

아래 링크에서 더 자세한 내용을 볼 수 있다.

Firebase 클라우드 메시징


1. firebase에서 프로젝트 만들기

밑 링크에서 Firebase 프로젝트를 만들고 '앱 추가'에서 만들 앱을 추가하고 google-services.json을 받는다.

Firebase Console

그리고 google-services.json을 "PROJECTNAME"\app\ 에 붙여넣기 해준다. (이 경로는 androidStudio에서가 아닌 파일 탐색기에서 찾는게 편할 것이다.)


2. build.gradle (:app), build.gradle ("PROJECTNAME")

2-1 build.gradle (:app)

dependencies {
        ...
    implementation 'com.google.firebase:firebase-messaging:11.0.4'
}

위와 같이 firebase의 라이브러리를 추가해준다.

2-2 build.gradle ("PROJECTNAME")

buildscript {
    repositories { ... }
    dependencies {
        ...
        classpath "com.google.gms:google-services:3.1.0"
    }
}

위와 같이 경로도 설정해준다.


3. FirebaseInstanceIDService.java

    ...
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
 
    private static final String TAG = "MyFirebaseIIDService";
 
    @Override
    public void onTokenRefresh() { //fcmToken 핸드폰에서 받아올 수 있는 난수 이 프로젝트에서 받아올 수 있다.
        super.onTokenRefresh();
    }
    private  void  sendRegistrationToServer(String token) {
 
    }
}

위 코드는 디바이스에서 token을 받는 역할을 한다.(위 동영상 강의에서는 다시 정의하지만 그렇게 하면 알람이 제대로 오지 않았다.)


4. FirebaseMessagingService.java

    ...
 
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
    private static final String TAG = "FirebaseMsgService";
    private String msg , title;
 
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "onMessageReceived");
 
        title = remoteMessage.getNotification().getTitle();
        msg = remoteMessage.getNotification().getBody();
 
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
 
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(msg)
                .setAutoCancel(true)
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setVibrate(new long[]{1, 1000});
 
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 
        notificationManager.notify(0, mBuilder.build());
 
        mBuilder.setContentIntent(contentIntent);
    }
}
 

위 FirebaseMessagingService는 push 알람 정보를 받아서 실제로 알람이 뜨게 해주는 역할을 한다.

11~12 - remoteMessage.getNotification().getTitle(), .getBody()를 통해서 제목과 내용을 반환받아서 변수에 저장한          다.

14~30 - 반환 받은 제목과 내용을 이용해서 Notification을 만들어 띄운다.

17 - PendingIntent을 사용하는 이유는 Intent를 NotificationManager에서 실행시키기 때문이다.

19~24 - NotificationCompat.Builder에서 알람의 요소들을 설정해준다.

26~28 - NotificationManager은 Builder로 만든 알람을 띄우는 역할을 한다.

자세한 내용은 밑의 두 링크에서 볼 수 있다.

안드로이드의 PendingIntent란? | 찰스의 안드로이드

[Android App 개발 스터디] Notification 예제


5. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.pushtest">
 
    <application
        ...
        <activity android:name=".MainActivity">
            ...
        </activity>
        <service android:name=".FirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <service android:name=".FirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
    </application>
</manifest>

10~14, 15~19 - 위에서 만든 service들을 여기 등록해준다.


6. gradle.properties

android.enableJetifier=true

위 코드를 gradle.properties에 추가해줘서 이 프로젝트에 추가한 androidx가 아닌 라이브러리를 androidx의 형태로 만든다.