programing

새로운 Firebase 클라우드 메시징 시스템이 포함된 알림 아이콘

procenter 2023. 7. 9. 22:38
반응형

새로운 Firebase 클라우드 메시징 시스템이 포함된 알림 아이콘

어제 구글은 구글 I/O에서 새로운 파이어베이스를 기반으로 한 새로운 알림 시스템을 선보였습니다.이 새로운 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());
    }

}

안타깝게도 이것은 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에서 메시지를 보내는 경우 언제든지 아이콘을 사용자 지정할 수 있습니다.

서버 구현을 사용하여 클라이언트에 메시지를 보내고 메시지의 통지 유형이 아닌 메시지의 데이터 유형을 사용합니다.

이렇게 하면 다음으로 전화를 받을 수 있습니다.onMessageReceived앱이 백그라운드에 있든 포그라운드에 있든 상관없이 사용자 지정 알림을 생성할 수 있습니다.

atm 그들은 그 이슈에 대해 일하고 있습니다. https://github.com/firebase/quickstart-android/issues/4

Firebase 콘솔에서 알림을 보낼 때는 기본적으로 앱 아이콘을 사용하고 Android 시스템은 알림 표시줄에서 해당 아이콘을 흰색으로 표시합니다.

이 결과가 만족스럽지 않으면 Firebase Messaging Service를 구현하고 메시지를 수신할 때 수동으로 알림을 생성해야 합니다.우리는 이것을 개선할 방법을 찾고 있지만 지금은 그것이 유일한 방법입니다.

편집: SDK 9.8.0을 사용하여 AndroidManifest.xml에 추가

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

제 솔루션은 Atom의 솔루션과 비슷하지만 구현하기가 더 쉽습니다.Firebase Messaging Service를 완전히 음영 처리하는 클래스를 만들 필요는 없습니다. 적어도 버전 9.6.1에서 Intent를 수신하는 메서드를 재정의하고 추가에서 표시할 정보를 가져오면 됩니다."해키" 부분은 메서드 이름이 실제로 난독화되어 있으며 Firebase sdk를 새 버전으로 업데이트할 때마다 변경되지만 Android Studio에서 Firebase Messaging Service를 검사하고 Intent를 유일한 매개 변수로 사용하는 공개 메서드를 찾아보면 빠르게 검색할 수 있습니다.버전 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());
    }
}

앱이 백그라운드에 있으면 알림 아이콘이 메시지 수신 메서드에 설정되지만 앱이 포그라운드에 있으면 알림 아이콘이 매니페스트에 정의된 아이콘이 됩니다.

enter image description here

targetSdkVersion을 19로 설정하면 됩니다.알림 아이콘에 색상이 지정됩니다.그런 다음 Firebase에서 이 문제를 해결할 때까지 기다립니다.

못생겼지만 작동하는 방법도 있습니다.FirebaseMessagingService.class를 압축 해제하고 해당 동작을 수정합니다.그런 다음 클래스를 당신의 앱에서 올바른 패키지에 넣고 덱스는 메시징 리브 자체의 클래스 대신 그것을 사용합니다.그것은 꽤 쉽고 효과적입니다.

방법은 다음과 같습니다.

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부터이며, 메소드는 난독화로 인해 버전에 따라 이름이 다릅니다.

이것을 쓰시오

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

밑에<application.....>

enter image description here

FCM 콘솔과 HTTP/JSON을 통해 동일한 결과로 알림을 트리거하고 있습니다.

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

알림 스크린샷

코드(SmallIcon 또는 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);
    }

제 문제는 간단하지만 알아차리기 어렵기 때문에 이 문제에 답을 추가하려고 생각했습니다.특히 기존 메타데이터 요소를 복사/붙여 사용자의 데이터를com.google.firebase.messaging.default_notification_iconandroid:value태그를 지정합니다.할 수 , 알림 에는 사용할 수 없습니다. 일단 변경한 후에android:resource모든 것이 예상대로 작동했습니다.

언급URL : https://stackoverflow.com/questions/37325051/notification-icon-with-the-new-firebase-cloud-messaging-system

반응형