[java] 푸시 알림 구현

푸시 알림은 사용자에게 중요한 정보를 실시간으로 전달하는 데 사용되는 기술입니다. Java를 사용하여 푸시 알림을 구현하는 방법을 알아보겠습니다.

1. Firebase Cloud Messaging (FCM) 설정

우선, FCM을 사용하여 푸시 알림을 보내기 위해 Firebase 프로젝트를 설정해야 합니다. Firebase 콘솔에 로그인하고, 새 프로젝트를 생성하고 안드로이드 앱을 추가하세요. 그런 다음, google-json 파일을 다운로드하여 프로젝트의 리소스 폴더에 저장하세요.

2. FCM 라이브러리 추가

Firebase Cloud Messaging을 사용하기 위해 Maven 또는 Gradle을 사용하여 FCM 라이브러리를 프로젝트에 추가합니다. Gradle을 사용하는 경우, build.gradle 파일에 다음 종속성을 추가하세요:

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

3. 푸시 알림 서비스 구현

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

public class MyFirebaseMessagingService extends FirebaseMessagingService {

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

        // 푸시 알림 메시지 처리 로직을 구현합니다.
        String title = remoteMessage.getNotification().getTitle();
        String message = remoteMessage.getNotification().getBody();

        // 사용자에게 푸시 알림을 표시하는 코드를 작성합니다.
        // 예를 들어, 알림매니저를 사용하여 푸시 알림을 표시할 수 있습니다.
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // 알림 채널 생성 (Android 8.0 이상에서 필요)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        // 푸시 알림 생성
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);

        // 알림을 표시
        notificationManager.notify(0, builder.build());
    }
}

위의 코드는 FCM으로부터 푸시 알림 메시지를 수신하고, 사용자에게 알림을 표시하는 방법을 보여줍니다. onMessageReceived() 메소드에서 푸시 알림 메시지를 처리하고 알림을 표시하는 코드를 작성하면 됩니다.

4. AndroidManifest.xml 수정

AndroidManifest.xml 파일에 푸시 알림 서비스를 등록해야 합니다. 다음과 같이 <application> 태그 안에 서비스를 추가하세요:

<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

5. 푸시 알림 테스트

이제 FCM을 사용하여 푸시 알림을 보낼 준비가 되었습니다. Firebase 콘솔에서 푸시 알림을 보내거나, 서버에서 API를 사용하여 푸시 알림을 보낼 수 있습니다. 앱이 백그라운드에 있을 때 푸시 알림을 수신하고 표시되는지 확인하세요.

참고 자료