마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

FCM 질문입니다. 최근 바뀌어서 아무리 찾아도 없네요.

0 추천

최근 instanceIDService인가가 없어지고 FirebaseMessagingService에서 다 관리하는 걸로 알고 있습니다.

백그라운드에서는 작 작동하는데 포그라운드에서 왜 작동이 안하는지 모르겠습니다. onMessageReceived() 메소드는 포그라운드일 때만 작동하는 거 아닌가요? 파이어베이스 가이드도 이상한 소리만 하고있고 누구 하나 가르쳐 줄 사람이 없어서 골치 아픕니다.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) { // 백그라운드 시 거치지 않는다. (포그라운드일 때만 작동)
        // TODO(developer): Handle FCM messages here.
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }
        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
    // [END receive_message]


    // [START on_new_token]
    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);
        sendRegistrationToServer(token);
    }
    // [END on_new_token]

    /**
     * Schedule a job using FirebaseJobDispatcher.
     */
    private void scheduleJob() {
        // [START dispatch_job]
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(MyJobService.class)
                .setTag("my-job-tag")
                .build();
        dispatcher.schedule(myJob);
        // [END dispatch_job]
    }

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }

    private void sendNotification(String title, String messageBody) {
        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);

        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.ic_launcher_background)
                        .setContentTitle(title)
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelName = getString(R.string.default_notification_channel_name);
            NotificationChannel channel = new NotificationChannel(channelId,
                    channelName,
                    NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0, notificationBuilder.build());
    }
}

제 FirebaseMessagingService입니다. 뭐가 잘못되었는지 체크해 주세용. sendNotification 메소드를 어디서, 어떻게 호출해야 할 지... ㅜ

익명사용자 님이 2019년 1월 25일 질문

2개의 답변

0 추천
안드로이드 코드에는 문제가 없어보이네요. 메니페스트파일에 서비스가 잘 정의되어있는지, 서버에서 페이로드를 잘 보내주고 있는지 확인해보시겠어요? 보통 포그라운드는 정상작동에 백그라운드만 안되면 페이로드에 노티/데이터를 함께사용하면 생기는 경우인데 반대경우는 새롭네요.
익명사용자 님이 2019년 1월 25일 답변
0 추천
제가 알기론 서버쪽에서 푸시 json payload 를 보셔야 하는 것으로 알고있습니다.

 

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

 

를 참고해보시면 notification 을 포함한 payload 일 경우

포어그라운드에서는 콜백 함수가 처리한다고 되어있습니당
안드로이드로우 (15,740 포인트) 님이 2019년 1월 25일 답변
...