Плохое уведомление: данный регион должен пересекаться с размерами растрового изображения - PullRequest
0 голосов
/ 01 марта 2019

Я получаю исключение по Crashlytics для небольшого количества пользователей.Для большинства пользователей это работает нормально, но для некоторых это не получается (небольшое количество, но я сейчас только на стадии подготовки).Я думаю, что проблема может заключаться в том, что я уменьшаю растровое изображение, которое я использую в уведомлении, я использую этот код для его уменьшения:

bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);

Исключение составляет следующее:

Fatal Exception: android.app.RemoteServiceException: Bad notification posted from package mypacakge: Couldn't inflate contentViewsjava.lang.IllegalArgumentException: The given region must intersect with the Bitmap's dimensions.
           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1881)
           at android.os.Handler.dispatchMessage(Handler.java:105)
           at android.os.Looper.loop(Looper.java:164)
           at android.app.ActivityThread.main(ActivityThread.java:6940)
           at java.lang.reflect.Method.invoke(Method.java)
           at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Что я делаю не так?

Спасибо.

Редактировать: Я выполнил поиск кода Android, чтобы определить, кто выдает это исключение, и он выглядит как Palette строитель, затем я искалкод, связанный с уведомлениями, который использует Palette и метод setRegion() и нашел это на MediaNotificationProcessor.java:

Palette.Builder paletteBuilder = Palette.from(bitmap)
                        .setRegion(0, 0, bitmap.getWidth() / 2, bitmap.getHeight())
                        .clearFilters() // we want all colors, red / white / black ones too!
                        .resizeBitmapArea(RESIZE_BITMAP_AREA);
                Palette palette = paletteBuilder.generate();
                backgroundColor = findBackgroundColorAndFilter(palette);
                // we want most of the full region again, slightly shifted to the right
                float textColorStartWidthFraction = 0.4f;
                paletteBuilder.setRegion((int) (bitmap.getWidth() * textColorStartWidthFraction), 0,
                        bitmap.getWidth(),
                        bitmap.getHeight());
                if (mFilteredBackgroundHsl != null) {
                    paletteBuilder.addFilter((rgb, hsl) -> {
                        // at least 10 degrees hue difference
                        float diff = Math.abs(hsl[0] - mFilteredBackgroundHsl[0]);
                        return diff > 10 && diff < 350;
                    });
                }

Так что я предполагаю, что здесь он передает какое-то плохое значение, но я понятия не имеюкакие.Я добавил еще несколько журналов для Fabric для этой ошибки, надеюсь, скоро я получу больше данных.

1 Ответ

0 голосов
/ 02 марта 2019

Это рабочий код, надеюсь, он вам или кому-то еще поможет ...

String CHANNEL_ID = "my_channel_xy";
CharSequence name = "my_channel";
String Description = "This is my channel";
int NOTIFICATION_ID = 19920901; 

Log.d("FileCreator : ","Notification Creating...:"+NOTIFICATION_ID);

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

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
      int importance = NotificationManager.IMPORTANCE_HIGH;
      NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
      mChannel.setDescription(Description);
      mChannel.enableLights(true);
      mChannel.setLightColor(Color.RED);
      mChannel.enableVibration(true);
      mChannel.setVibrationPattern(new long[]{100});
      mChannel.setShowBadge(true);

      if (notificationManager != null)
      {
           notificationManager.createNotificationChannel(mChannel);
      }

}

Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra("MYVAR", "MYVAL");
resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

//resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("NextTitle")
                    .setContentText("NextText")
                    .setTicker("NextText")
                    .setStyle(new NotificationCompat.BigTextStyle().bigText("NextMessage it is a long text which is replaced when user swipes it down from the notification tray..."))
                    .setSmallIcon(R.drawable.ic_mynotification)
                    .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher))
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE)
                    .setContentIntent(resultPendingIntent)
                    .setAutoCancel(false)
                    .setOngoing(true)
                    .setOnlyAlertOnce(true)
                    .setColor(getResources().getColor(android.R.color.holo_red_dark));

if (notificationManager != null)
{
      notificationManager.notify(NOTIFICATION_ID, builder.build());
      Log.d("FileCreator : ", "NOTIFIED TO THE USER... \n");
}
else
{
      Log.d("FileCreator : ", "COULD NOT BE NOTIFIED TO THE USER...????!!!! \n");
}

Это должно работать на всех устройствах с обоими значками в уведомлениях.

...