Звук уведомления не воспроизводится. Отказ в разрешении - PullRequest
0 голосов
/ 11 ноября 2018

Пользовательский звук уведомления не работает. Звук из внутреннего хранилища, владелец файла не мое приложение.

Код:

    Uri sound = Uri.parse(account.notifySound); 
    // "account.notifySound" contains path to audio file, obtained from ringtone picker 

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_new_message)
            .setContentTitle(messageTitle)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(sound)
            .setContentIntent(pendingIntent);

    if (account.notifyLedColor > 0) notificationBuilder.setLights(MainActivity.ledColorsList[account.notifyLedColor - 1], 100, 50);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(tag, 0, notificationBuilder.build());

Ошибка:

java.lang.SecurityException: Permission Denial: reading com.android.fileexplorer.provider.FileExplorerFileProvider uri content://com.android.fileexplorer.myprovider/external_files/zedge/notification_sound/Marbles.mp3 from pid=1874, uid=1000 requires the provider be exported, or grantUriPermission()
        at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:616)
        at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:483)
        at android.content.ContentProvider$Transport.enforceFilePermission(ContentProvider.java:474)
        at android.content.ContentProvider$Transport.openTypedAssetFile(ContentProvider.java:419)
        at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:313)
        at android.os.Binder.execTransact(Binder.java:569)
2018-11-11 16:08:20.613 756-15193/? E/MediaPlayerService: Couldn't open fd for content://com.android.fileexplorer.myprovider/external_files/zedge/notification_sound/Marbles.mp3
2018-11-11 16:08:20.613 1874-23378/? E/MediaPlayer: Unable to create media player

minSdkVersion 21

Как это исправить?

UPD:

Я добавил после "Uri sound = Uri.parse (account.notifySound);":

 grantUriPermission("com.android.systemui", sound, Intent.FLAG_GRANT_READ_URI_PERMISSION); 

И получил ошибку:

 java.lang.SecurityException: Uid 10204 does not have permission to uri 0 @ content://com.android.fileexplorer.myprovider/external_files/zedge/notification_sound/Marbles.mp3

UPD2:

Функция выбора мелодии звонка открыла несколько проводников звука, например, «Музыка», «Темы», снова «Музыка» - еще один проводник звука, отличающийся от первого «Музыка» ...

И когда я выбираю звук в «Музыке», выбираю звукUri =:

содержание: //com.android.fileexplorer.myprovider/external_files/zedge/notification_sound/Snapchat_Tone-04a0409e-68c4-4294-beb3-bb137b8d5886.mp3

При выборе звука в «Темах» выбирается uri:

Файл: ///storage/emulated/0/MIUI/.ringtone/Snapchat_Tone-04a0409e-68c4-4294-beb3-bb137b8d5886.mp3

Этот звук воспроизводится, когда Uri начинается с «file: ///» (проводник звука «Themes»), и получает ошибку, когда Uri начинает «content: //» (проводник звука «Music»).

Хотя некоторые другие файлы воспроизводятся при выборе в «Музыка» с Uri начинается «content: // ...»

1 Ответ

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

Как сказал компилятор:

требует экспорта провайдера или grantUriPermission ()

Вы можете попробовать это:

grantUriPermission("com.android.systemui", sound,
    Intent.FLAG_GRANT_READ_URI_PERMISSION);

гдеsound - это Uri, который вы используете с setSound ().

Если вы не можете быть уверены, какие пакеты должны предоставлять разрешение, ниже функционал помощника будет выполнять цикл поиска:

public static void grantUriPermission(Activity ctx, Intent intent, Uri uri, int permissionFlags) {
    List<ResolveInfo> resolvedIntentActivities = ctx.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

    for (ResolveInfo resolvedIntentInfo : resolvedIntentActivities) {
        String packageName = resolvedIntentInfo.activityInfo.packageName;

        ctx.grantUriPermission(packageName, uri, permissionFlags);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...