IT story

Android 푸시 알림 : 알림에 아이콘이 표시되지 않고 흰색 사각형이 대신 표시됨

hot-time 2020. 6. 12. 19:24
반응형

Android 푸시 알림 : 알림에 아이콘이 표시되지 않고 흰색 사각형이 대신 표시됨


내 앱이 알림을 생성하지만 해당 알림에 설정 한 아이콘이 표시되지 않습니다. 대신 흰색 사각형이 나타납니다.

아이콘의 PNG 크기를 조정하려고했습니다 (치수 720x720, 66x66, 44x44, 22x22). 흥미롭게도 더 작은 치수를 사용할 때 흰색 사각형이 더 작습니다.

알림을 생성하는 올바른 방법뿐만 아니라이 문제를 Google에서 확인했으며 코드를 읽은 내용이 정확해야합니다. 안타깝게도 상황은 그렇지 않습니다.

내 휴대폰은 Android 5.1.1이 설치된 Nexus 5입니다. 에뮬레이터, Android 5.0.1의 Samsung Galaxy s4 및 Android 5.0.1의 Motorola Moto G에도 문제가 있습니다 (모두 빌려 왔으며 현재 가지고 있지 않습니다)

알림 코드와 두 개의 스크린 샷이 이어집니다. 자세한 정보가 필요하면 언제든지 문의하십시오.

모두 감사합니다.

@SuppressLint("NewApi") private void sendNotification(String msg, String title, String link, Bundle bundle) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
    resultIntent.putExtras(bundle);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            resultIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    Notification notification;
    Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound);
    notification = new Notification.Builder(this)
                .setSmallIcon(R.drawable.lg_logo)
                .setContentTitle(title)
                .setStyle(new Notification.BigTextStyle().bigText(msg))
                .setAutoCancel(true)
                .setContentText(msg)
                .setContentIntent(contentIntent)
                .setSound(sound)
                .build();
    notificationManager.notify(0, notification);
}

알림을 열지 않고 알림이 열렸습니다


원인 : 5.0 Lollipop의 경우 "알림 아이콘이 완전히 흰색이어야합니다".

대상 SDK를 20으로 설정하여 흰색 아이콘 문제를 해결하면 앱에서 Android Lollipop을 타겟팅하지 않으므로 Lollipop 관련 기능을 사용할 수 없습니다.

대상 SDK 21 솔루션

Lollipop Material Icons를 지원하려면 Lollipop 이상 버전의 투명 아이콘을 만드십시오. https://design.google.com/icons/를 참조하십시오.

http://developer.android.com/design/style/iconography.html을 살펴보면 흰색 스타일이 Android Lollipop에 알림이 표시되는 방식임을 알 수 있습니다.

Lollipop에서 Google은 흰색 알림 아이콘 뒤에 표시 될 색상을 사용하도록 제안합니다. 링크 참조 : https://developer.android.com/about/versions/android-5.0-changes.html

색상을 추가하려는 모든 곳 https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#setColor(int)

Lollipop OS 버전 이하의 Notification Builder 구현은 다음과 같습니다.

Notification notification = new NotificationCompat.Builder(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    notification.setSmallIcon(R.drawable.icon_transperent);
    notification.setColor(getResources().getColor(R.color.notification_color));
} else { 
    notification.setSmallIcon(R.drawable.icon);
} 

참고 : setColor는 Lollipop에서만 사용할 수 있으며 아이콘의 배경에만 영향을줍니다.

그것은 당신의 문제를 완전히 해결할 것입니다!


Google 클라우드 메시징을 사용하는 경우 단순히 아이콘을 변경 해도이 문제 가 해결되지 않습니다 . 예를 들어, 다음과 같이 작동하지 않습니다.

 Notification notification  = new Notification.Builder(this)
                .setContentTitle(title)
                .setContentText(text)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentIntent(pIntent)
                .setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE)
                .setAutoCancel(true)
                .build();

ic_notification이 투명하고 흰색 인 경우에도 마찬가지입니다. 다음과 같이 매니페스트 메타 데이터에도 정의해야합니다.

  <meta-data android:name="com.google.firebase.messaging.default_notification_icon"

            android:resource="@drawable/ic_notification" />

메타 데이터는 application태그 아래에 있습니다.


Google의 디자인 가이드 라인을 따르는 것이 좋습니다 .

이는 말한다 "알림 아이콘이 완전히 흰색이어야합니다."


Android Manifest에서이 코드를 선언하십시오.

<meta-data android:name="com.google.firebase.messaging.default_notification_icon" 

android:resource="@drawable/ic_stat_name" />

나는 이것이 당신에게 도움이되기를 바랍니다.


우리는 아래와 같이 할 수 있습니다 :

setSmallIcon()아래 코드와 같이 알림 작성기 객체를 새로 작성하고 알림 작성기 객체를 사용하여 호출하십시오 .

앱을 설치할 OS 버전을 확인할 방법을 만듭니다. Lolipop, 즉 API 21 아래에 있으면 배경색이있는 일반 앱 아이콘이 표시되고 배경이없는 투명한 앱 아이콘이 표시됩니다. 따라서 os 버전> = 21을 사용하는 장치 setColor()는 알림 빌더 클래스의 메소드 사용하여 아이콘의 배경색을 설정합니다 .

샘플 코드 :

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);

notificationBuilder.setSmallIcon(getNotificationIcon(notificationBuilder));

private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
             int color = 0x008000;
             notificationBuilder.setColor(color);
             return R.drawable.app_icon_lolipop_above;

    } 
    return R.drawable.app_icon_lolipop_below;
}

 <meta-data android:name="com.google.firebase.messaging.default_notification_icon"

        android:resource="@drawable/ic_notification" />

응용 프로그램 블록의 manifest.xml 파일에이 줄을 추가하십시오


롤리팝 지원 알림 아이콘을 제공하려면 두 가지 유형의 알림 아이콘을 만드십시오.

  1. 일반 알림 아이콘 : 아래 롤리팝 버전 용.
  2. 투명 배경이있는 알림 아이콘 : 롤리팝 이상 버전.

이제 OS 버전에서 런타임에 적절한 아이콘을 알림 빌더로 설정하십시오.

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    mBuilder.setSmallIcon(R.drawable.ic_push_notification_transperent);
} else {
    mBuilder.setSmallIcon(R.drawable.ic_push_notification);
}

마지막 으로이 문제에 대한 해결책을 얻었습니다.

이 문제는 앱이 전혀 실행되고 있지 않은 경우에만 발생합니다. (배경이나 전경 모두) . 앱이 포 그라운드 또는 백그라운드에서 실행될알림 아이콘이 제대로 표시됩니다 (흰색 사각형이 아님).

따라서 우리가 설정 한 것은 프론트 엔드 API와 동일한 알림 아이콘 구성입니다.

프론트 엔드에서는 React Native를 사용 했으며 푸시 알림에는 react-native-fcm npm package를 사용했습니다 .

FCM.on("notification", notif => {
   FCM.presentLocalNotification({
       body: notif.fcm.body,
       title: notif.fcm.title,
       big_text: notif.fcm.body,
       priority: "high",
       large_icon: "notification_icon", // notification icon
       icon: "notification_icon",
       show_in_foreground: true,
       color: '#8bc34b',
       vibrate: 300,
       lights: true,
       status: notif.status
   });
});

우리는 사용했습니다 FCM 푸시 NPM 패키지 사용 되는 Node.js를 푸시 알림을위한 백엔드로 다음과 같이 페이로드 구조를 설정합니다.

{
  to: '/topics/user', // required
  data: {
    id:212,
    message: 'test message',
    title: 'test title'
  },
  notification: {
    title: 'test title',
    body: 'test message',
    icon : 'notification_icon', // same name as mentioned in the front end
    color : '#8bc34b',
    click_action : "BROADCAST"
  }
}

기본적으로 Android 시스템에 로컬로 저장된 notification_icon 이미지를 검색합니다.


이 시도

나는 같은 문제에 직면했지만 많은 답을 시도했지만 해결책을 얻지 못했습니다. 마침내 문제를 해결할 수있는 방법을 찾았습니다.

-투명한 배경의 알림 아이콘 만들기. 앱의 너비와 높이는 아래 크기와 같아야하며 프로젝트-> 응용 프로그램-> src-> 메인-> 결과에 붙여 넣으십시오

  • MDPI 24 * 24

  • HDPI 36 * 36

  • XHDPI 48 * 48

  • XXHDPI 72 * 72


위의 후에이 메시지를 onMessageReceived 메소드에 붙여 넣으십시오.


Intent intent = new Intent(this, News.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            {
                notificationBuilder.setSmallIcon(R.drawable.notify)
                                      //            .setContentTitle(title)
                            //                        .setContentText(message)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);
            } else
                {
                    notificationBuilder.setSmallIcon(R.drawable.notify)
                       //                                .setContentTitle(title)
                        //                        .setContentText(message)
                            .setAutoCancel(true)
                            .setSound(defaultSoundUri)
                            .setContentIntent(pendingIntent);
            }
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notificationBuilder.build());

매니페스트 파일에이 코드를 추가하는 것을 잊지 마십시오

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

알림은 아래 설명 된대로 회색조 입니다. 그들은 다른 사람들이 쓴 것에도 불구하고 흑백이 아닙니다. 네트워크 강도 막대와 같이 여러 가지 음영이있는 아이콘을 보셨을 것입니다.

API 21 (Lollipop 5.0) 이전에는 색상 아이콘이 작동합니다. 애플리케이션이 API 20을 대상으로하도록 강요 할 수 있지만 애플리케이션에서 사용할 수있는 기능이 제한되므로 권장되지 않습니다. 실행중인 API 레벨을 테스트하고 컬러 아이콘 또는 그레이 스케일 아이콘을 적절하게 설정할 수 있지만 그만한 가치는 없습니다. 대부분의 경우 그레이 스케일 아이콘을 사용하는 것이 가장 좋습니다.

이미지에는 RGBA (빨강 / 녹색 / 파랑 / 알파)의 4 개 채널이 있습니다. 알림 아이콘의 경우 Android는 R, G 및 B 채널을 무시합니다. 카운트하는 유일한 채널은 불투명도라고도하는 알파입니다. 그림 색상의 알파 값을 제어 할 수있는 편집기로 아이콘을 디자인하십시오.

알파 값이 그레이 스케일 이미지를 생성하는 방법 :

  • Alpha = 0 (투명) —이 픽셀은 투명하며 배경색을 나타냅니다.
  • Alpha = 255 (불투명) —이 픽셀은 흰색입니다.
  • Alpha = 1 ... 254 —이 픽셀은 정확히 예상 한 것이므로 투명과 흰색 사이의 음영을 제공합니다.

로 변경 setColor:

  • 전화하십시오 NotificationCompat.Builder.setColor(int argb). 의 설명서에서 Notification.color:

    이 알림을 표시 할 때 표준 스타일 템플릿에서 적용 할 강조 색상 (색상 상수와 같은 ARGB 정수)입니다. 현재 템플릿 디자인은이 색상의 필드 위에 아이콘 이미지 (흰색으로 스텐실)를 오버레이하여 화려한 헤더 이미지를 구성합니다. 알파 성분은 무시됩니다.

    setColor를 사용한 테스트에서 알파 구성 요소는 무시 되지 않습니다 . 알파 값이 높을수록 픽셀이 흰색으로 바뀝니다. 알파 값이 낮 으면 픽셀이 알림 영역의 배경색 (장치의 검은 색) 또는 풀다운 알림의 지정된 색으로 바뀝니다.


흰색 아이콘을 생성 할 수있는 링크를 찾았습니다.

이 링크를 사용하여 실행기 아이콘의 흰색 아이콘을 생성하십시오.

링크를 열고 ic_launcher 또는 알림 아이콘을 업로드하십시오.


아래 코드를 추가하여 문제를 해결했습니다.

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

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

ic_stat_nameAndroid Studio 에서 생성 된 위치 res >> New >> Image Assets >> IconType (Notification)을 마우스 오른쪽 버튼으로 클릭하십시오.

알림 페이로드가있는 서버 PHP 측에서해야 할 한 가지 단계

$message = [
    "message" => [
        "notification" => [
            "body"  => $title , 
            "title" => $message
        ],

        "token" => $token,

    "android" => [
           "notification" => [
            "sound"  => "default",
            "icon"  => "ic_stat_name"
            ]
        ],

       "data" => [
            "title" => $title,
            "message" => $message
         ]


    ]
];

섹션 참고

    "android" => [
           "notification" => [
            "sound"  => "default",
            "icon"  => "ic_stat_name"
            ]
        ]

여기서 아이콘 이름은 "icon" => "ic_stat_name"매니페스트에서 동일하게 설정되어야합니다.


이 문제를 해결하기위한 요구 사항 :

  1. 이미지 형식 : 32 비트 PNG (알파 포함)

  2. 이미지는 투명해야합니다

  3. 투명도 색상 색인 : 흰색 (FFFFFF)

출처 : http://gr1350.blogspot.com/2017/01/problem-with-setsmallicon.html


버전마다 다른 아이콘을 사용할 수 있습니다. 다음과 같이 아이콘에 로직을 설정하십시오.

int icon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.colored_: R.drawable.white_tint_icon_for_lolipop_or_upper;

SDK> = 23의 경우 setLargeIcon을 추가하십시오

notification = new Notification.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(context.getResources(), R.drawable.lg_logo))
            .setContentTitle(title)
            .setStyle(new Notification.BigTextStyle().bigText(msg))
            .setAutoCancel(true)
            .setContentText(msg)
            .setContentIntent(contentIntent)
            .setSound(sound)
            .build();

(Android Studio 3.5) 최신 버전의 Android Studio 인 경우 알림 이미지를 생성 할 수 있습니다. res 폴더 > New> Image Asset을 마우스 오른쪽 버튼으로 클릭하십시오 . 그러면 아래 이미지와 같이 이미지 자산 구성이 표시됩니다. 아이콘 유형알림 아이콘으로 변경하십시오 . 이미지는 흰색이고 투명해야합니다. 이미지 자산 구성 은 해당 규칙을 시행합니다. 중요 사항 : 클라우드 / 푸시 알림에 아이콘을 사용하려면 새로 작성된 알림 아이콘을 사용하려면 애플리케이션 태그 아래에 메타 데이터를 추가해야합니다.이미지 자산 구성

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

화려한 아이콘을 유지하려는 경우-해결 방법 아이콘
에 약간 다른 색상의 픽셀을 추가하십시오.
제 경우에는 음영과 빛이있는 검은 색 아이콘이 있습니다. 진한 파란색 픽셀을 추가하면 작동합니다.


안드로이드 8.0에서 비슷한 문제가 있습니다. WHITE 아이콘 리소스를 사용해보십시오. 아이콘에 컬러 이미지를 사용하려고 할 때 흰색 사각형이 표시됩니다. 흰색 아이콘으로 바꾸면 작업이 시작됩니다.


SDK 특정 버전을 줄이려면 다음과 같이하면됩니다. ( '#'을 '0x'로 교체)

Notification notification = new NotificationCompat.Builder(this);
notification.setSmallIcon(R.drawable.icon_transperent);
notification.setColor(0x169AB9); //for color: #169AB9

참고 URL : https://stackoverflow.com/questions/30795431/android-push-notifications-icon-not-displaying-in-notification-white-square-sh

반응형