본문 바로가기
Android

Android FCM 연동하기 (2)

by square_man_tile 2021. 1. 26.
728x90
반응형

지난 포스팅에서 FCM 관련 설정들을 잔뜩 해주었습니다.

boxster718.tistory.com/12?category=915277

 

Android FCM 연동하기 (1)

푸시메시지. 플레이스토어에 등록되어있는 거의 모든 앱이 가지고 있는 기능입니다. 우리도 이걸 만들어봅시다. 먼저, 푸시메시지 기능을 탑재하고싶은 앱을 준비합니다. 이 앱에서 우린 SHA-1

boxster718.tistory.com

이제, 안드로이드 프로젝트 내에 FCM 서비스를 등록해보겠습니다.

먼저 MyFirebaseMessaging.java 파일을 생성합니다.

이 파일은 FirebaseMessagingService를 상속받습니다.

public class MyFirebaseMessaging extends FirebaseMessagingService {
	
}

 

Ctrl+O (알파벳 O)를 누르면, 창이 하나 뜹니다.

여기에서

이렇게 세개를 선택해준 뒤 ( Ctrl+클릭하면 여러개 선택 됩니다. ) OK를 눌러 창을 닫습니다.

package com.example.fcmapp;

import androidx.annotation.NonNull;

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

public class MyFirebaseMessaging extends FirebaseMessagingService {
    public MyFirebaseMessaging() {
        super();
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }

    @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);
    }
}

그럼 이런 화면이 출력됩니다.

onMessageReceived에서는 푸시메시지 수신시 할 작업을 작성해주면 되고,

onNewToken에서는 이 기기의 토큰이 바뀌었을 때 할 작업을 작성해주면 됩니다.

보통 onNewToken에서는 서버로 변경된 키값을 전달합니다.

 

마지막으로 MyFirebaseMessaging.java 파일을 서비스로 등록해줘야합니다.

Manifest로 이동합니다.

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.FCMApp">
        
        <service android:name=".MyFirebaseMessaging">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        
</application>

application 레벨에 <service> 항목을 추가해줍니다.

다시 MainActivity로 이동합니다.

Intent fcm = new Intent(getApplicationContext(), MyFirebaseMessaging.class);
startService(fcm);

onCreate 안에 위와 같은 내용을 추가해줍니다.

이제 앱이 실행되면 FCM 서비스를 실행하게되었습니다.

 

MyFirebaseMessaging.java 파일에서 푸시메시지 수신시 알림 팝업을 하는 방법은 다음 포스팅에서 작성하겠습니다.

 

감사합니다.

 

728x90
반응형
LIST