我的MainActivity中有以下代码。
Log.d("FILES", Environment.getExternalStorageDirectory().getAbsolutePath());
Log.d("FILES", Environment.getRootDirectory().getAbsolutePath());
Log.d("FILES", Arrays.toString(Environment.getRootDirectory().list()));
Log.d("FILES", Arrays.toString(Environment.getExternalStorageDirectory().list()));
Log.d("FILES", Environment.getExternalStorageState());
Log.d("FILES", String.valueOf(Environment.getExternalStorageDirectory().listFiles() != null));
aboce代码在logcat中显示如下输出:
12-28 08:38:51.344 23429-23429/com.tahsinalsayeed.codeviewer D/FILES: /storage/emulated/0
12-28 08:38:51.344 23429-23429/com.tahsinalsayeed.codeviewer D/FILES: /system
12-28 08:38:51.344 23429-23429/com.tahsinalsayeed.codeviewer D/FILES: [lost+found, app, bin, build.prop, data, etc, fonts, framework, lib, media, plugin, preloadres, priv-app, recovery-from-boot.p, res, tts, usr, vendor, xbin]
12-28 08:38:51.347 23429-23429/com.tahsinalsayeed.codeviewer D/FILES: null
12-28 08:38:51.353 23429-23429/com.tahsinalsayeed.codeviewer D/FILES: mounted
12-28 08:38:51.356 23429-23429/com.tahsinalsayeed.codeviewer D/FILES: false
为什么我无法在getExternalStorageDir下列出文件,我无法做出正面或反面。根据对this问题的接受答案,这应该有效。我的清单中有以下权限。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
我已经使用API 23在物理设备和模拟器上进行了测试。
答案 0 :(得分:0)
在Android 6.0( API级别23 )中,用户在应用运行时向应用授予权限,而不是在安装应用时授予权限。
注意:清单中的提及权限在 API 23 中无效,您需要在运行时询问权限。
请关注此官方链接here
askForPermission(Manifest.permission.READ_EXTERNAL_STORAGE,100);
询问用户许可的方法
private void askForPermission(String permission, Integer requestCode) {
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
//This is called if user has denied the permission before
//In this case I am just asking the permission again
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
} else {
Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
}
}
要处理权限请求的结果,请调用onRequestPermissionsResult
方法。它的代码如下:
注意:返回结果时,会检查是否授予了权限。如果是,则传递requestCode。
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED) {
//permission granted
} else {
//Permission Denied
}
}