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

#java #android #android-studio #notifications #android-notifications

#java #Android #android-studio #уведомления #android-уведомления

Вопрос:

В моем приложении есть службы, которые используются для оповещения пользователя при подключении зарядного устройства, но проблема в том, что пользовательский звук не работает с некоторыми устройствами, даже если все они имеют версию Android 8. Мой код: `

     public void notification(Intent intent) {
 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,-1);
   
 boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ;

    Intent enterApp_intent = new Intent(getApplicationContext(),MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0,enterApp_intent,0);

    Bitmap largeIcon = BitmapFactory.decodeResource(getApplicationContext().getResources(),R.drawable.main_icon);

    NotificationCompat.Builder charging_builder = new 

    NotificationCompat.Builder(getApplicationContext());
    charging_builder.setContentTitle("Title");
    charging_builder.setContentText("Content Text");
    charging_builder.setContentIntent(pendingIntent);
    charging_builder.setLargeIcon(largeIcon);
    charging_builder.setSmallIcon(R.drawable.null_shape);
    charging_builder.setDefaults(NotificationManager.IMPORTANCE_MAX);
    charging_builder.setColor(Color.parseColor("#1fd699"));
    charging_builder.setOngoing(false);

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

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){

        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .build();

        NotificationChannel charging_notificationChanel = new NotificationChannel("charging_battery","charging battery",
                NotificationManager.IMPORTANCE_DEFAULT);
        charging_notificationChanel.setDescription("Charging notification");
        charging_notificationChanel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE "://" getBaseContext().getPackageName() "/" 
                R.raw.charging_notification),audioAttributes);

        charging_notificationChanel.enableVibration(false);
        charging_notificationChanel.enableLights(true);

        notificationManager.createNotificationChannel(charging_notificationChanel);
        charging_builder.setChannelId("charging_battery");
    }

    if(isCharging){ // charging
        notificationManager.notify(19,charging_builder.build());
    }
}`
 

Уведомление отображается на всех устройствах, но на некоторых устройствах SAMSUNG нет звука?
и все это работает с API 26. почему это?

Комментарии:

1. пожалуйста, сообщите модель или марку вашего устройства.

2. @sinaakbary это samsung

Ответ №1:

Как вы можете видеть в разделе Создание и управление уведомлением: если вы нацелены на Android 8.0 (уровень API 26) и отправляете уведомление без указания канала уведомления, уведомление не отображается, и система регистрирует ошибку.

На всякий случай вы можете попробовать это, возможно, вам нужно добавить свой идентификатор канала в манифест примерно так:

<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />

Ответ №2:

Убедитесь, что вы выполняете эти две вещи:

  1. Правильный путь такой: channel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE «://» getPackageName() «/raw/ ice»), att);
  2. Всякий раз, когда вы вносите какие-либо изменения в конфигурацию канала уведомлений, либо переустановите приложение, либо очистите данные.
  3. Убедитесь, что вы добавляете оба Channel.setSound и NotificationCompat.Builder.setSound вместе

Комментарии:

1. Все коды верны. и, как я уже сказал, звук работает с некоторыми устройствами, и переустановка приложения ничего не изменила. спасибо за ответ

2. убедитесь, что вы добавили channel.setSound и Notification. Конструктор. Установите оба звука вместе, потому что на некоторых устройствах channel.set sound не работает