이 튜토리얼에서는 안드로이드 애플리케이션에서 Firebase 클라우드 메시징(Firebase Cloud Messaging, FCM)을 사용해 서버에서 보낸 메시지를 수신하고 알림으로 표시하는 방법을 단계별로 알아봅니다.
사전 준비 사항
코드를 작성하기 전에 다음 사항이 준비되어 있어야 합니다.
- Firebase 콘솔에서 프로젝트를 생성하고 안드로이드 앱을 등록한 뒤
google-services.json파일을 프로젝트의app/폴더에 추가 - 프로젝트 수준과 앱 수준의
build.gradle에 Google 서비스 플러그인 및 Firebase 메시징 의존성(firebase-messaging) 추가 - 새로운 프로젝트라면 기존 지원 라이브러리(support library) 대신 AndroidX 라이브러리를 사용하는 것이 좋습니다
1단계: 새 프로젝트 생성
Android Studio를 실행하고 File → New Project를 선택한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계: MainActivity 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다. 이 예제에서는 기본적인 화면만 설정합니다.
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
3단계: MyFirebaseMessagingService 작성
메시지를 수신하고 알림을 표시하는 핵심 클래스입니다. src/MyFirebaseMessagingService.java 파일을 생성하고 다음 코드를 추가합니다.
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.json.JSONObject;
import java.util.Map;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onNewToken(String s) {
// 새 디바이스 토큰이 발급될 때 호출됩니다.
Log.e("NEW_TOKEN", s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
Log.e("JSON_OBJECT", object.toString());
String NOTIFICATION_CHANNEL_ID = "sairam";
long[] pattern = {0, 1000, 500, 1000};
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Android 8.0(Oreo) 이상에서는 알림 채널 생성이 필수입니다.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"Your Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(pattern);
notificationChannel.enableVibration(true);
mNotificationManager.createNotificationChannel(notificationChannel);
}
// 방해 금지(DND) 모드 관련 채널 설정
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel =
mNotificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID);
channel.canBypassDnd();
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage.getNotification().getBody())
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setAutoCancel(true);
mNotificationManager.notify(1000, notificationBuilder.build());
}
}
주요 포인트 정리
- onNewToken(): 기기마다 고유한 FCM 등록 토큰이 발급되거나 갱신될 때 호출됩니다. 이 토큰을 서버에 전송해 두면 특정 기기로 메시지를 보낼 수 있습니다.
- onMessageReceived(): 데이터 페이로드(data payload)가 포함된 메시지가 도착할 때 호출됩니다. 여기서 데이터를 파싱하고 알림을 직접 구성해 표시합니다.
- 알림 채널(Notification Channel): Android 8.0(API 26)부터는 반드시 채널을 생성해야 알림이 표시되므로, SDK 버전을 확인한 뒤 채널을 만들어 줍니다.
4단계: 매니페스트에 서비스 등록
AndroidManifest.xml의 <application> 태그 안에 아래와 같이 서비스를 등록해야 시스템이 해당 서비스를 인식할 수 있습니다.
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 옵션 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기에 앱이 설치·실행되어 기본 화면이 표시됩니다.

이후 Firebase 콘솔의 Cloud Messaging 메뉴나 서버에서 테스트 메시지를 전송하면, 위에서 구현한 서비스가 메시지를 수신해 기기에 푸시 알림이 나타나는 것을 확인할 수 있습니다.