ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
为什么我使用以上的代码获取不到我手机里面的音乐? 调试发现 musicResolver.query() 是这个函数有问题,然后进入这个函数后,发现内部的变量 cursor 为 null
,没有找到本地的音乐文件?那要用什么方法得到本地的音乐文件信息?
PHPz2017-04-18 09:21:16
Maybe it’s a problem with my phone. Today I used my classmate’s code, and I was able to get the music on his phone. Then I downloaded the code to my 荣耀7
上就不行,我又把代码下到另外一个同学荣耀8
phone, but it didn’t work either. Sure enough, it’s a problem with the phone. It’s not a code problem, so I searched for related articles and finally found it:
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
Put the above code into the class where you want to search for music files. When you finally search for music, just call the above method. The above means to check whether there are corresponding permissions. If there are no corresponding permissions, increase the permissions (it is indeed a permission issue, but I didn’t expect that other phones can run normally. The two current Honor phones cannot run. It’s a trap and a waste. I have a lot of time,,,)
Finally put the following code in
manifest
.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
For now, it should be fine. If not, you can send me a private message.