我希望在屏幕上弹出通知时播放声音。我可以从创建的下拉列表中获取声音(String
格式),但是即使将其解析为Uri
,声音也不会播放。请帮忙。
这是读取音乐文件的外部存储的代码:
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
String[] projection = {
MediaStore.Audio.Media.TITLE,
};
EnableRuntimePermission();
Cursor cursor = this.managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
null);
spin.setOnItemSelectedListener(this);
List<String> songs = new ArrayList<String>();
while (cursor.moveToNext()) {
songs.add(cursor.getString(0));
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, songs);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(dataAdapter);
public void EnableRuntimePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(
Pop_up_2.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Toast.makeText(Pop_up_2.this, "Now you can read music files", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(Pop_up_2.this, new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE}, RequestPermissionCode);
}
}
@Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(Pop_up_2.this, "Permission Granted, Now your application can access music.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Pop_up_2.this, "Permission Cancelled, Now your application cannot access music.", Toast.LENGTH_LONG).show();
}
break;
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item1 = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
用于构建和显示通知的代码:
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_today_black_24dp)
.setContentTitle("Hello there ")
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSound(Uri.parse(item1));
NotificationManagerCompat notification=NotificationManagerCompat.from(context);
notification.notify(NOTIFICATION_ID,builder.build());
AndroidManifest中声明的权限列表:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />