NotificationCompat.Builder () не принимает идентификатор канала в качестве аргумента - PullRequest
0 голосов
/ 04 ноября 2018

Я знаю, что этот вопрос задавался несколько раз раньше. Но ни одно из решений не помогло мне. Вот почему я хотел бы задать вопрос еще раз. Следующая строка принимает только NotificationCompat.Builder(context):

 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, ADMIN_CHANNEL_ID)  // Getting error

Я выполнил:

  • импорт android.support.v4.app.NotificationCompat
  • Версия моей библиотеки поддержки выше 25

    implementation group: 'com.android.support', name: 'appcompat-v7', version: '27.1.1

  • SDK для Compile & Target выше 25

    android { compileSdkVersion(27) buildToolsVersion '27.0.3' flavorDimensions 'default' dataBinding { enabled = true } defaultConfig { applicationId('something') minSdkVersion(16) targetSdkVersion(27) versionCode(1) versionName('1.0.0') testInstrumentationRunner('android.support.test.runner.AndroidJUnitRunner') multiDexEnabled true } Но все равно получаю ошибку. Что я должен сделать, чтобы это исправить? Пожалуйста, помогите.

Ответы [ 3 ]

0 голосов
/ 04 ноября 2018

Сначала создайте канал уведомлений и идентификатор канала передачи уведомлений.

  NotificationManager notificationManager = (NotificationManager)context
                     .getSystemService(Context.NOTIFICATION_SERVICE);
  buildNotificationChannel(manager,String <Channel_ID>,String description);

Создать канал уведомлений.

 public void buildNotificationChannel(NotificationManager manager, String channelID, 
       String description) {
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
             if (manager.getNotificationChannel(channelID) == null) {
               NotificationChannel channel = new NotificationChannel(channelID, 
               description,NotificationManager.IMPORTANCE_LOW);
               channel.setDescription(description);
               manager.createNotificationChannel(channel);
           }
      }
  }

Создать уведомление, передавая аргумент ID канала

     Notification notification = new 
     NotificationCompat.Builder(context,<Channel_ID>)
        .setSmallIcon(R.drawable.app_icon)
        .setContentTitle("Title goes here.")
        .setPriority(Notification.PRIORITY_HIGH)
        .setContentIntent(pendingIntent)
        .setAutoCancel(false)
        .setOngoing(true)
        .setVisibility(Notification.VISIBILITY_PUBLIC)
        .setContentText("Content Text").build();
        notificationManager.notify(ID,notification);
0 голосов
/ 04 ноября 2018

Решение:

В Android 8.0 (Oreo) у вас должно быть что-то, называемое NotificationChannel. Попробуйте следующую реализацию:

Step1: Создать канал уведомлений

private void createNotificationChannel() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

Наконец: Тогда ваше уведомление:

 NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(activity)
                .setSmallIcon(R.drawable.ic_launcher_background) // notification icon
                .setContentTitle("Notification!") // title for notification
                .setContentText("Hello word") // message for notification
                .setAutoCancel(true); // clear notification after click
Intent intent = new Intent(activity, RecorderActivity.class);
PendingIntent pi = PendingIntent.getActivity(activity,0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pi);
notificationManager.notify(1, mBuilder.build());

Пожалуйста, сравните это с Вашим и посмотрите, работает ли оно

Попробуйте, надеюсь, это поможет.

0 голосов
/ 04 ноября 2018

Насколько я знаю, вы можете добавить канал уведомлений только для версий больше или равных 26, версии ниже Android 8.0 не поддерживают канал уведомлений. Мое предложение будет использовать следующие коды:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
           { 
             NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, ADMIN_CHANNEL_ID) 
           }

    else NotificationCompat.Builder(context)
...