개요
이 튜토리얼에서는 Android에서 Firebase 푸시 알림을 수신한 후 사용자가 알림을 탭했을 때 특정 액티비티(Activity)를 열도록 처리하는 방법을 단계별로 살펴봅니다.
핵심 원리는 간단합니다. 알림이 도착하면 PendingIntent에 대상 액티비티 정보를 담아두고, 사용자가 알림을 클릭하면 해당 인텐트가 실행되어 원하는 화면으로 이동하는 구조입니다.
구현 단계
1단계 — 새 프로젝트 생성
Android Studio에서 File ⇒ New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.
2단계 — Firebase 메시징 서비스 작성
src/MyFirebaseMessagingService.java 파일에 아래 코드를 추가합니다. 이 서비스는 푸시 메시지를 수신하고, 알림 채널을 생성한 뒤, 클릭 시 MainActivity를 열도록 설정합니다.
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
@Override
public void onNewToken(String s) {
super.onNewToken(s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// 알림 클릭 시 열릴 액티비티 지정
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.putExtra("NotificationMessage", "I am from Notification");
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent resultIntent = PendingIntent.getActivity(
getApplicationContext(), 0, notificationIntent, 0);
// 알림 빌더 구성
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext(), default_notification_channel_id)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Test")
.setContentText("Hello! This is my first push notification")
.setContentIntent(resultIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Android 8.0(Oreo) 이상에서는 알림 채널 필수
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
}
}코드 핵심 포인트
- PendingIntent 설정:
PendingIntent.getActivity()를 사용해 알림 클릭 시 실행될 인텐트를 미리 준비합니다.putExtra()로 데이터를 함께 전달할 수 있습니다. - 인텐트 플래그:
FLAG_ACTIVITY_CLEAR_TOP과FLAG_ACTIVITY_SINGLE_TOP을 조합하면 이미 액티비티가 실행 중일 때 중복 생성 없이 기존 인스턴스를 재사용합니다. - 알림 채널: Android 8.0(API 26)부터는 반드시
NotificationChannel을 생성해야 알림이 정상적으로 표시됩니다. - 데이터 수신:
MainActivity의onCreate()또는onNewIntent()에서getIntent().getStringExtra("NotificationMessage")로 전달된 값을 확인할 수 있습니다.
마지막으로 AndroidManifest.xml에 해당 서비스를 등록하는 것을 잊지 마세요. 이렇게 하면 푸시 알림을 받았을 때 사용자가 알림을 탭하여 바로 원하는 액티비티로 진입할 수 있습니다.