Android App

FirebaseCloudMessaging (푸시 알림) in Android Studio

YunSeong 2021. 8. 16. 18:05
728x90
반응형

https://youtu.be/pPMEgVarhWU

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

 

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

https://firebase.google.com/docs/cloud-messaging?hl=ko 

 

Firebase 클라우드 메시징

Firebase 클라우드 메시징(FCM)은 무료로 메시지를 안정적으로 전송할 수 있는 교차 플랫폼 메시징 솔루션입니다.

firebase.google.com

 


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

 

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

https://console.firebase.google.com/

 

로그인 - Google 계정

하나의 계정으로 모든 Google 서비스를 Google 계정으로 로그인

accounts.google.com

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

 


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

2-1 build.gradle (:app)

1
2
3
4
dependencies {
        ...
    implementation 'com.google.firebase:firebase-messaging:11.0.4'
}
cs

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

 

2-2 build.gradle ("PROJECTNAME")

1
2
3
4
5
6
7
buildscript {
    repositories { ... }
    dependencies {
        ...
        classpath "com.google.gms:google-services:3.1.0"
    }
}
cs

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

 


3. FirebaseInstanceIDService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
    ...
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
 
    private static final String TAG = "MyFirebaseIIDService";
 
    @Override
    public void onTokenRefresh() { //fcmToken 핸드폰에서 받아올 수 있는 난수 이 프로젝트에서 받아올 수 있다.
        super.onTokenRefresh();
    }
    private  void  sendRegistrationToServer(String token) {
 
    }
}
cs

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

 


4. FirebaseMessagingService.java

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
32
33
    ...
 
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(this0new 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[]{11000});
 
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 
        notificationManager.notify(0, mBuilder.build());
 
        mBuilder.setContentIntent(contentIntent);
    }
}
 
cs

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

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

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

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

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

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

 

 

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

https://www.charlezz.com/?p=861 

 

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

PendingIntent PendingIntent는 Intent를 가지고 있는 클래스로, 기본 목적은 다른 애플리케이션(다른 프로세스)의 권한을 허가하여 가지고 있는 Intent를 마치 본인 앱의 프로세스에서 실행하는 것처럼 사

www.charlezz.com

https://animoto1.tistory.com/entry/Android-App-%EA%B0%9C%EB%B0%9C-%EC%8A%A4%ED%84%B0%EB%94%94-Notification-%EC%98%88%EC%A0%9C?category=957109 

 

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

notification을 통해 휴대폰 알림을 만들 수 있다. (1) activity_main.xml 액티비티에 버튼을 한 개 생성하여 버튼을 클릭하면 알림이 뜨도록 만들어 볼 것이다. (2) Main..

animoto1.tistory.com


5. AndroidManifest.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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>
cs

 

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

 


6. gradle.properties

1
android.enableJetifier=true
cs

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

 

 

728x90
반응형