Android 9 Api 28 Уведомление не отображается - PullRequest
0 голосов
/ 27 мая 2019

Я пытаюсь показать уведомление, но оно не работает как для версии Oreo, так и для Pie.

Это работает в версии kitkat.

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

Вот мой код:

String idChannel = "my_channel_01";
        Intent mainIntent;
        mainIntent = new Intent(ChecklistOptionActivity.this, CashCountOptionActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);

        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationChannel mChannel = null;
        // The id of the channel.

        int importance = NotificationManager.IMPORTANCE_HIGH;

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentTitle(context.getString(R.string.app_name))
                .setSmallIcon(R.drawable.bc_icon)
                .setContentIntent(pendingIntent)
                .setContentText("Test");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(idChannel, context.getString(R.string.app_name), importance);
            // Configure the notification channel.
            mChannel.setDescription("Test");
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.RED);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mNotificationManager.createNotificationChannel(mChannel);
        } else {
            builder.setContentTitle(context.getString(R.string.app_name))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setColor(ContextCompat.getColor(context, R.color.colorBlue))
                    .setVibrate(new long[]{100, 250})
                    .setLights(Color.YELLOW, 500, 5000)
                    .setAutoCancel(true);
        }
        mNotificationManager.notify(1, builder.build());

1 Ответ

0 голосов
/ 27 мая 2019
String channel_id = createNotificationChannel(context); 

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id);

Приведенный ниже метод заключается в создании нового channel_id.

 public static String createNotificationChannel(Context context) {

                // NotificationChannels are required for Notifications on O (API 26) and above.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                    // The id of the channel.
                    String channelId = "Channel_id";

                    // The user-visible name of the channel.
                    CharSequence channelName = "Application_name";
                    // The user-visible description of the channel.
                    String channelDescription = "Application_name Alert";
                    int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
                    boolean channelEnableVibrate = true;
        //            int channelLockscreenVisibility = Notification.;

                    // Initializes NotificationChannel.
                    NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
                    notificationChannel.setDescription(channelDescription);
                    notificationChannel.enableVibration(channelEnableVibrate);
        //            notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);

                    // Adds NotificationChannel to system. Attempting to create an existing notification
                    // channel with its original values performs no operation, so it's safe to perform the
                    // below sequence.
                    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    assert notificationManager != null;
                    notificationManager.createNotificationChannel(notificationChannel);

                    return channelId;
                } else {
                    // Returns null for pre-O (26) devices.
                    return null;
                }
            }
  • Здесь вы получите push-уведомление, используя channel_id на вашем устройстве, которое состоит из 26+ версии SDK.
  • Поскольку NotificationCompat.Builder(context) является устаревшим методом, теперь вы будете использовать обновленную версию, имеющую два параметра, один из которых является контекстом, а другой - channel_id.
  • NotificationCompat.Builder(context, channel_id) обновленный метод.попробуйте.
  • В 26+ версии SDK устройства вы будете каждый раз создавать channel_id.
...