Android Почему уведомление не работает в более ранней версии Oreo?

Я ссылаюсь на это уведомление из этого URL-адреса документации по Android. . пытаюсь создать простое уведомление, но, похоже, этот код предназначен для oreo и выше. Но как мне обрабатывать уведомление для версии ниже?

Ниже приведен код, который я запускаю при нажатии кнопки:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, PRIMARY_CHANNEL)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("My notification")
                .setContentText("Much longer text that cannot fit one line...")
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText("Much longer text that cannot fit one line..."))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.feroz_channel_name);
            String description = getString(R.string.feroz_channel_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(PRIMARY_CHANNEL, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager1 = getSystemService(NotificationManager.class);
            notificationManager1.createNotificationChannel(channel);
        }
// notificationId is a unique int for each notification that you must define
        notificationManager.notify(123, mBuilder.build());

он отлично работает на версии Android oreo и pie, но как я могу включить версии ниже?

ниже приведено исключение, которое я получаю, если запускаю вышеупомянутый код в следующих версиях oreo:

Process: sample.androido.com.myapplication, PID: 14596
    android.app.RemoteServiceException: Bad notification posted from package sample.androido.com.myapplication: Couldn't create icon: StatusBarIcon(icon=Icon(typ=RESOURCE pkg=sample.androido.com.myapplication id=0x7f0f0000) visible user=0 )
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1517)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5443)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
NotificationCompat.Builder(this) попробуй с этим конструктором. При желании вы можете проверить с помощью NotificationManager вместо NotificationManagerCompat.
grabarz121 11.02.2019 15:23
0
1
842
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

поместите маленький значок уведомления в доступные папки.

To provide support for all Android versions, developers should: Place status bar icons for Android 3.0 and later in the drawable...

проверить документация

значок не виден, когда я выбираю из рисунков, я взял png с размером 16 * 16, он становится серым, но изображение не отображается

Feroz Siddiqui 11.02.2019 15:18

используйте этот тип уведомления....

if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
        Notification builder = new NotificationCompat.Builder(ctx, 
  notification.CHANNEL_ID_ONE)
                .setContentTitle(title)
                .setContentText(Artist)
                .setLargeIcon(bitmap1)
                .setSmallIcon(R.drawable.back)
                .addAction(R.drawable.play,"back",pi)
                .addAction(R.drawable.play,"play",pendingIntent)
                .addAction(R.drawable.play,"next",PI)
                .build();
        NotificationManager notificationManager = (NotificationManager) 
 ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(111, builder);
    }else{
        Notification notification = new NotificationCompat.Builder(ctx)
                .setContentTitle(title)
                .setContentText(Artist)
                .setLargeIcon(bitmap1)
                .setSmallIcon(R.drawable.back)
                .addAction(R.drawable.play,"back",pi)
                .addAction(R.drawable.play,"play",pendingIntent)
                .addAction(R.drawable.play,"next",PI)
                .build();
        NotificationManager notificationManager = (NotificationManager) 
ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(111, notification);
    }

Вы знаете, как настроить уведомление в Oreo, поэтому код блока else для вас, это определенно поможет вам

Другие вопросы по теме