可能这在 Lolipop/Kitkat 之前有效,但我没有测试它。我正在我的 xperia m2 aqua 上的棉花糖上测试它,它没有显示我的可移动 sdcard 中的音乐,所以,我从 sdCard 复制了两首音乐到内部存储,它正在显示这两首音乐。其他音乐播放器在手机上运行良好。下面是我的代码:
public class ListviewActivity extends AppCompatActivity {
ListView listView;
String[] items;
ArrayAdapter<String> arrayAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_songs);
listView= (ListView) findViewById(R.id.listView);
ArrayList<File> mySongs = findSong(Environment.getExternalStorageDirectory());
Log.d("myLog"," "+Environment.getExternalStorageState());
Log.d("myLog"," "+Environment.getExternalStorageDirectory());
Log.d("myLog"," "+Environment.getExternalStorageDirectory().getAbsolutePath());
items = new String[mySongs.size()];
for (int i = 0; i < mySongs.size(); i++) {
Toast.makeText(this, " "+mySongs.get(i).getName().toString(), Toast.LENGTH_SHORT).show();
// items[i] = mySongs.get(i).getName().toString();
items[i] = mySongs.get(i).getName().toString();
}
arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
Log.d("myLog"," "+items);
listView.setAdapter(arrayAdapter);
}
public ArrayList<File> findSong(File root) {
ArrayList<File> al = new ArrayList<File>();
File[] files = root.listFiles(); // All file and folder automatic collect
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSong(singleFile)); //Recursively call
} else {
if (singleFile.getName().endsWith(".mp3")) {
al.add(singleFile);
}
}
}
return al;
}
}
来自上述代码结果的 Log.d
mounted
/storage/emulated/0
/storage/emulated/0
清单许可
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
和 Permisson 以编程方式用于 Marshmallow 及更高版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
}else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 738);
}
}
结果 它只显示来自内部存储的歌曲。我已将两首歌曲添加到内部存储以进行检查,并且显示。尽管我已经设置了权限和所有工作代码,为什么不从 sdCard 读取?
更新
@Manoj 已将此问题标记为可能重复,但事实并非如此。我已经给予了适当的许可,如果用户也点击了拒绝,那么下次它会再次询问。在我的代码中,我使用 if/else 来获得许可,我认为@Manoj 没有清楚地看到它。