새로운 Firebase Cloud Messaging 시스템이 포함 된 알림 아이콘


132

어제 Google은 Google I / O에서 새로운 Firebase를 기반으로하는 새로운 알림 시스템을 발표했습니다. 이 새로운 FCM (Firebase Cloud Messaging)을 Github의 예제와 함께 사용해 보았습니다.

알림의 아이콘은 특정 드로어 블을 선언했지만 항상 ic_launcher입니다.

왜 ? 메시지 처리를위한 공식 코드는 다음과 같습니다.

public class AppFirebaseMessagingService extends FirebaseMessagingService {

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // If the application is in the foreground handle both data and notification messages here.
        // 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.
        sendNotification(remoteMessage);
    }
    // [END receive_message]

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param remoteMessage FCM RemoteMessage received.
     */
    private void sendNotification(RemoteMessage remoteMessage) {

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

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

// this is a my insertion looking for a solution
        int icon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.myicon: R.mipmap.myicon;
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(icon)
                .setContentTitle(remoteMessage.getFrom())
                .setContentText(remoteMessage.getNotification().getBody())
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

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

}

중포 기지 당신은 통지를 생성하는 방법을 함께 할 수 없다,에 같은 이미지를 제공하십시오 당신이보고있는
— tyczj

1
정확한. 이 코드는 Firebase에서 직접 제공되며 sendNotification () 메소드는 모든 알림에 대해 동일합니다. 이 코드는 GCM에서 제대로 작동하지만 FCM 번호에서는 작동하지 않습니다. 항상 새로운 웹 인터페이스를 사용하여 메시지를 보내는 ic_launcher로 유지됩니다
— marco

당신이 FCM과 아무 상관이 푸시 페이로드의 알림 태그 푸시를 전송하지 않는 한 당신은 작은 아이콘이 아니라 큰 아이콘을 설정
— tyczj

앱이 포 그라운드에있을 때 사용자 지정 알림 아이콘이 표시됩니까? 그것은 나를 위해 작동합니다. 그러나 앱이 백그라운드에있는 경우 모든 알림 설정이 무시되므로 (아이콘, 사운드, 조명, 진동 등은 사용자 지정할 수 없으므로) 일종의 기본 FCM 핸들러를 사용해야합니다.
— shinypenguin

답변:


267

불행히도 이것은 SDK 9.0.0-9.6.1에서 Firebase 알림의 제한 사항이었습니다. 앱이 백그라운드에 있으면 실행기 아이콘은 콘솔에서 보낸 메시지에 대한 매니페스트 (필요한 Android 색조 포함)에서 사용됩니다.

그러나 SDK 9.8.0에서는 기본값을 무시할 수 있습니다! AndroidManifest.xml에서 다음 필드를 설정하여 아이콘과 색상을 사용자 정의 할 수 있습니다.

<meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/google_blue" />

앱이 포 그라운드에 있거나 데이터 메시지가 전송되는 경우 자체 로직을 사용하여 디스플레이를 사용자 지정할 수 있습니다. HTTP / XMPP API에서 메시지를 보내는 경우 항상 아이콘을 사용자 정의 할 수 있습니다.


1
@Ian Barber : 가까운 시일 내에이 행동을 바꾸려는 Google의 계획은 무엇입니까?
— skylve 2016 년

1
팀은 문제를 알고 수정을 위해 노력하고 있습니다.
— Arthur Thompson

1
이것에 대한 업데이트? Google 엔지니어가 단순히 패치를 푸시하는 것을 잊어 버린 상황이 있었기 때문에 묻습니다.
— CQM

7
아, 9.8.0에서 작동하도록했습니다. 다른 사람을 돕기 위해 상태 표시 줄 아이콘은 developer.android.com/guide/practices/ui_guidelines/… 요구 사항을 충족해야합니다 . 광산은 그렇지 않았으므로 firebase는 매니페스트에 지정된 아이콘을 사용하는 대신 표준 흰색 사각형으로 기본 설정합니다.
— zaifrun

3
이 작업을 시도한 후 아이콘이 다른 알림보다 작은 경우 PNG가 아닌 벡터 드로어 블을 사용하고 있는지 확인하십시오. 그것은 나를 위해 그것을 해결했다.
— 익는

35

서버 구현을 사용하여 클라이언트에 메시지를 보내고 알림 유형의 메시지가 아닌 데이터 유형의 메시지를 사용하십시오 .

onMessageReceived앱이 백그라운드 또는 포 그라운드에 있고 사용자 정의 알림을 생성 할 수 있는지 여부 에 관계없이 콜백을 얻는 데 도움이됩니다.


2
이것은 Firebase 문서에서도 제안 된 솔루션입니다. 알림 대신 데이터 푸시에 의존하는 경우 원하는 방식으로 알림을 표시 할 수 있습니다.
— racs

1
네 동의합니다. 정답으로 표시해야합니다. 또는 내 대답은 아래에 있습니다 :)
— 개발하십시오.

3
아니요, 알림을 기대하는 다른 클라이언트 / 레거시 버전과의 호환성을 유지해야하는 사람들에게는 적합하지 않습니다.
— Gabor

프로덕션에는 이미 알림 유형의 푸시를 기대하는 앱이 있으며 새로운 클라이언트에 대한 데이터를 추가하기 위해 (복잡한) 백엔드 구성 요소를 확장했습니다. 그러나 기존 버전의 앱에 대한 지원은 제거 할 수 없습니다.
— Gabor

오 동의합니다. 또 다른 문제입니다. 통합하기 전에 문서를 철저히 읽는 것이 좋습니다. 또한 생산하기 전에 철저히 테스트하십시오. 앱을 실행하기 전에 테스트 한 경우 문제를 피할 수있었습니다. 어쨌든, 당신은 배울 것이 있습니다.
— geekoraul

9

atm 그들은 그 문제에 대해 작업하고 있습니다 https://github.com/firebase/quickstart-android/issues/4

Firebase 콘솔에서 알림을 보내면 기본적으로 앱 아이콘이 사용되며 알림 표시 줄에 있으면 Android 시스템이 해당 아이콘을 흰색으로 바꿉니다.

결과가 마음에 들지 않으면 FirebaseMessagingService를 구현하고 메시지를받을 때 수동으로 알림을 작성해야합니다. 우리는 이것을 개선하기 위해 노력하고 있지만 현재로서는 이것이 유일한 방법입니다.

편집 : SDK 9.8.0으로 AndroidManifest.xml에 추가

<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/my_favorite_pic"/>

멜로에 사용자 정의 아이콘 알림 트레이를 표시하는 방법
— Harsha

6

내 솔루션은 ATom의 솔루션과 유사하지만 구현하기가 더 쉽습니다. FirebaseMessagingService를 완전히 가리는 클래스를 만들 필요는 없습니다. 인 텐트 (적어도 버전 9.6.1에서는 공개)를 수신하는 메소드를 재정의하고 추가 정보에서 표시 할 정보를 가져올 수 있습니다. "해킹"부분은 메소드 이름이 실제로 난독 화되어 Firebase SDK를 새 버전으로 업데이트 할 때마다 변경되지만 Android Studio로 FirebaseMessagingService를 검사하고 필요한 공개 메소드를 찾아서 빠르게 찾을 수 있다는 것입니다. 유일한 매개 변수로서의 의도. 버전 9.6.1에서는 zzm이라고합니다. 내 서비스는 다음과 같습니다.

public class MyNotificationService extends FirebaseMessagingService {

    public void onMessageReceived(RemoteMessage remoteMessage) {
        // do nothing
    }

    @Override
    public void zzm(Intent intent) {
        Intent launchIntent = new Intent(this, SplashScreenActivity.class);
        launchIntent.setAction(Intent.ACTION_MAIN);
        launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* R    equest code */, launchIntent,
                PendingIntent.FLAG_ONE_SHOT);
        Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_notification)
                .setLargeIcon(rawBitmap)
                .setContentTitle(intent.getStringExtra("gcm.notification.title"))
                .setContentText(intent.getStringExtra("gcm.notification.body"))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

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

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

키 이름에 대한 gcm.notification.title은 모든 버전에서 100 % 안전합니까?
— pedroooo

3

targetSdkVersion을 19로 설정하십시오. 알림 아이콘이 색상으로 표시됩니다. 그런 다음 Firebase가이 문제를 해결하기를 기다립니다.


7
: D 와우, 부작용 목록은 어디에 있습니까?
— Eugen Pechanec

@EugenPechanec 예, 트레이드 오프는 20+ 이상에서 사용 가능한 일부 API를 사용하지 못할 수 있다는 것입니다.
— benleung

3

추악하지만 작동하는 방법도 하나 있습니다. FirebaseMessagingService.class를 디 컴파일하고 동작을 수정하십시오. 그런 다음 클래스를 yout 앱의 올바른 패키지에 넣고 dex는 메시징 라이브러리 자체의 클래스 대신 클래스를 사용하십시오. 아주 쉽고 일하고 있습니다.

방법이 있습니다 :

private void zzo(Intent intent) {
    Bundle bundle = intent.getExtras();
    bundle.remove("android.support.content.wakelockid");
    if (zza.zzac(bundle)) {  // true if msg is notification sent from FirebaseConsole
        if (!zza.zzdc((Context)this)) { // true if app is on foreground
            zza.zzer((Context)this).zzas(bundle); // create notification
            return;
        }
        // parse notification data to allow use it in onMessageReceived whe app is on foreground
        if (FirebaseMessagingService.zzav(bundle)) {
            zzb.zzo((Context)this, intent);
        }
    }
    this.onMessageReceived(new RemoteMessage(bundle));
}

이 코드는 버전 9.4.0의 코드이며, 난독 화로 인해 다른 버전의 이름이 다른 메소드가 있습니다.


3

앱이 백그라운드에있는 경우 알림 아이콘은 Message Receive 메소드에 설정되지만 앱이 포 그라운드에있는 경우 알림 아이콘은 매니페스트에 정의한 것입니다.

여기에 이미지 설명을 입력하십시오


2

FCM 콘솔과 HTTP / JSON ...에서 같은 결과로 알림을 트리거합니다.

제목, 전체 메시지를 처리 ​​할 수 ​​있지만 아이콘은 항상 기본 흰색 원입니다.

알림 스크린 샷

코드의 사용자 정의 아이콘 (setSmallIcon 또는 setSmallIcon) 또는 앱의 기본 아이콘 대신 :

 Intent intent = new Intent(this, MainActivity.class);
    // use System.currentTimeMillis() to have a unique ID for the pending intent
    PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);

    if (Build.VERSION.SDK_INT < 16) {
        Notification n  = new Notification.Builder(this)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pIntent)
                .setAutoCancel(true).getNotification();
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //notificationManager.notify(0, n);
        notificationManager.notify(id, n);
    } else {
        Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        Notification n  = new Notification.Builder(this)
                .setContentTitle(messageTitle)
                .setContentText(messageBody)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setLargeIcon(bm)
                .setContentIntent(pIntent)
                .setAutoCancel(true).build();

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //notificationManager.notify(0, n);
        notificationManager.notify(id, n);
    }

1
알았다! 내 <서비스> 태그 내가 뜨거운 응답 여기의 AndroidManifest.xml에서 <응용 프로그램> 태그를 벗어 stackoverflow.com/a/37352142/6366150
— 곤잘로

백그라운드에서 여전히 동일한 이전 동작을 보이는 전경 앱 실행에서만 작동
— Gonzalo

사용자 정의 알림 아이콘이 작동하고 제대로 작동하지만 앱 배경에서 흰색 사각형 아이콘이 표시되는 forground의 앱이 도와주세요
— Harsha

1

이것을 쓰십시오

<meta-data 
         android:name="com.google.firebase.messaging.default_notification_icon"
         android:resource="@drawable/ic_notification" />

바로 아래 <application.....>

여기에 이미지 설명을 입력하십시오


0

내 문제는 간단하지만 눈에 띄지 않기 때문에 이것에 대한 답변을 추가 할 것이라고 생각했습니다. 특히 my를 만들 때 기존 메타 데이터 요소를 복사 / 붙여 넣기 com.google.firebase.messaging.default_notification_icon하여 android:value태그를 사용하여 값을 지정했습니다. 알림 아이콘에는 작동하지 않으며 일단 알림 아이콘을 변경하면 android:resource예상대로 작동합니다.


동일은 간다 default_notification_color메타, 그것은 할 필요가 android:resource로 설정 - android:value하지 작업을합니다
— flochtililoch
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.