개발 - 안드로이드

안드로이드 FCM 포그라운드 전체 사용자 notification 예제 #02

개미v 2023. 9. 9. 18:28

앱이 포그라운드 상태에서도(백그라운드 + 포그라운드) FCM notification 알림을 받을 수 있는 방법입니다.

 

포그라운드 전체 사용자 notification

두번째 예제는 FCM으로 포그라운드 notification을 전체 사용자에게 보내는 방법입니다.

 

앱 내부에서 FCM notification 처리가 될 수 있도록 onMessageReceived 메소드를 추가해 보겠습니다.
이전 내용 포함해서 전체로 올립니다.

build.gradle (Project)
기존 파일에서 plugin 추가

plugins {
    id 'com.google.gms.google-services' version '4.3.15' apply false
}


build.gradle(Module:app)
기존 파일에서 plugin과 dependency 추가

plugins {
    id 'com.google.gms.google-services'
}

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


AndroidManifest.xml
기존 파일에서 notification 권한과 서비스 추가
(FirebaseMessagingService 서비스는 새로 작성하는 소스임)

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

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


MainActivity.java
앱 실행시 처음 부분에서 FCM SDK 초기화를 호출 해줘야 합니다.

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        FirebaseApp.initializeApp(this);
        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(@NonNull Task<String> task) {
                        String newToken = task.getResult();
                    }
                });
    }
}


FirebaseMessagingService.java
앱 내부에서 FCM notification 처리가 될 수 있도록 onMessageReceived 메소드를 구현 하면 됩니다.

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

    // FCM 토큰 발급
    @Override
    public void onNewToken(@NonNull String token) {
        super.onNewToken(token);

        // (선택) 기기 또는 서버에 토큰 저장
    }

    // FCM 푸시 메시지 처리
    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {

        // notification
        if (remoteMessage.getNotification() != null) {
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }

        // data
        if (remoteMessage.getData().size() > 0) {
            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
        }
    }

    // FCM 푸시 메시지를 앱에서 알림
    private void sendNotification(String title, String body) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);

        String chId = "myChId";
        String chName = "myChName";

        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notiBuilder = new NotificationCompat.Builder(this, chId)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(body)
                .setAutoCancel(true)
                .setSound(soundUri)
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(chId, chName, NotificationManager.IMPORTANCE_HIGH);
        manager.createNotificationChannel(channel);
        manager.notify(0, notiBuilder.build());
    }
}


Firebase console에서 메시지 보내기
Messaging 메뉴에서 메시지를 보내면 등록된 앱의 전체 사용자에게 notification을 보냅니다.


결과 화면
이제는 앱이 포그라운드 상태에서도 Notification 알림이 뜹니다.

 

해석

앱이 포그라운드 상태에서는 onMessageReceived 메소드에서 notification과 data 메시지를 처리 합니다.


자세한 내용은 아래 표 참고 하시기 바랍니다.

 

다음장에서는 FCM 메시지를 Firebase Console이 아닌 스프링 서버에서 보내는 방법을 해보겠습니다.