본문 바로가기
안드로이드

[Android] FCM 알림 구현

by 코딩히어로 2022. 8. 31.
728x90

1


 

이전 포스팅을 통해 서버에서 Android로 FCM 알림을 보내는 방법에 대해 알아봤습니다

리눅스 Centos 서버의 php를 통해서 notification으로 fcm을 전송하는 방법은 다음 포스팅에서 확인 가능합니다

2021.12.13 - [언어/PHP] - 리눅스 FCM push message 전송

 

리눅스 FCM push message 전송

리눅스 Centos7에서 FCM메시지를 전송하기 위해서 PHP를 사용했지만 진행하는 프로젝트가 TCP/IP C언어 프로그램에서 전송해야 되는 시스템이라 다음과 같이 구성하였습니다. C언어에서는 curl 라이브

codinghero.tistory.com

 

이렇게 보낸 FCM 메시지를 안드로이드에서는 알림으로 띄워줄 수 있어야 합니다

기본적으로 안드로이드에 Firebase를 설정하는 방법에 대해서는 아래 공식 홈페이지에 자세하게 나와있습니다

https://firebase.google.com/docs/cloud-messaging?hl=ko

 

Firebase 클라우드 메시징

Firebase 클라우드 메시징(FCM)은 무료로 메시지를 안정적으로 전송할 수 있는 크로스 플랫폼 메시징 솔루션입니다.

firebase.google.com

 

기본 설정까지 완료했다면 이제 본격적으로 메시지를 받아서 알림 창에 띄워주어야 합니다

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);
        Log.i("디버깅","Refreshed token = "+s);
    }

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

    private void sendNotification(String datakind) {
        
    }

}

제일 먼저 안드로이드를 설정하면서 MyFirebaseMessagingService를 생성했습니다

여기에는 3가지 항목이 구성되는데 새로운 토큰을 만들어주는 onNewToken,

메시지가 서버로부터 전달되었을 때 호출되는 onMessageReceived,

전달된 메시지를 처리하는 구문인 sendNotification

 

먼저 안드로이드 어플이 실행되어 발행된 토큰이 없다면 onNewToken이 호출되어 현재

안드로이드 기기의 고유 Token값을 생성하게 됩니다

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);
        Log.i("디버깅","Refreshed token = "+s);
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        uper.onMessageReceived(remoteMessage);
        if(remoteMessage.getData().size()>0){
            PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
            @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP,"TAG");
            wakeLock.acquire(3000);
            sendNotification(remoteMessage.getData().get("message"));
        }
        if(remoteMessage.getNotification()!=null){
            sendNotification(remoteMessage.getNotification().getBody());
        }
    }

    private void sendNotification(String datakind) {
        
    }

}

이제 onMessageReceived를 구현해야 할 차례입니다

이곳에서는 remoteMessage를 판별하여 전달된 메시지가 어떠한 종료인지를 판별하여 처리합니다

만약 key값으로 Data가 함께 전달된 경우 어플의 화면을 wakeLock을 해준 뒤에

sendNotification으로 message를 전달합니다

 

그렇지 않을 경우에는 sendNotification만 호출해주는데 결국에는 onMessageReceived에서는 화면 켜짐에

대한 처리만 해주고 나머지는 sendNotification에서 알림 팝업을 띄워주는 작업을 합니다

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);
        Log.i("디버깅","Refreshed token = "+s);
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        uper.onMessageReceived(remoteMessage);
        if(remoteMessage.getData().size()>0){
            PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
            @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP,"TAG");
            wakeLock.acquire(3000);
            sendNotification(remoteMessage.getData().get("message"));
        }
        if(remoteMessage.getNotification()!=null){
            sendNotification(remoteMessage.getNotification().getBody());
        }
    }

    private void sendNotification(String datakind) {
        Intent intent = new Intent(this, ScreenViewFlip.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);


        long now = System.currentTimeMillis();
        Date date = new Date(now);
        String kindstr="";
        String kindstr1="";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.KOREAN);
        if(datakind.contains("1")){
            kindstr = dateFormat.format(date)+"\n차량에 충격이 발생하였습니다";
            kindstr1 = "차량에 충격이 발생하였습니다";
        }else if(datakind.contains("2")){
            kindstr = dateFormat.format(date)+"\n차량에 전압이 낮습니다";
            kindstr1 = "차량에 전압이 낮습니다";
        }else if(datakind.contains("3")) {
            kindstr = dateFormat.format(date) + "\n저전압 시동이 발생하였습니다";
            kindstr1 = "저전압 시동이 발생하였습니다";
        }else if(datakind.contains("4")){
            kindstr = dateFormat.format(date) + "\n" + datakind;
            kindstr1 = "마이키 공지사항이 등록되었습니다.";
        }

        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.icons)
                        .setContentTitle(kindstr1)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

}

이렇게 전달된 remoteMessage를 통해 데이터의 종류를 판별하고 그에 따른 문구를 지정하여 알림을 띄워줍니다

이러한 처리는 sendNotification에서 담당합니다

제 경우에는 데이터를 1~4로 전달하고 그에따른 알림 문구를 지정해주었지만 서버에서 직접

message에 문구를 첨부하고 안드로이드에서는 출력만 하도록 할 수도 있습니다

728x90
반응형

댓글