[英]Path to App own directory in External Storage
In a library, I want to return a file that represents App own directory in External Storage, the directory that is returned by this method: 在库中,我想返回一个表示外部存储中App自己的目录的文件,该方法返回的目录:
context.getExternalFilesDir(null);
But using this method before API Level 19, needs WRITE_EXTERNAL_STORAGE
permission and I do not want to force user to use this permission, specially my method only want to return abstract File and does not want to create directory. 但是在API级别19之前使用此方法,需要
WRITE_EXTERNAL_STORAGE
权限,我不想强制用户使用此权限,特别是我的方法只想返回抽象文件而不想创建目录。
I can use this code: 我可以使用这段代码:
Environment.getExternalStorageDirectory().getCanonicalPath() + "/Android/data/" + packageName + "/files";
But I think hard coding is not safe.Is there a way to return that directory without forcing user to use WRITE
permission? 但我认为硬编码不安全。有没有办法在不强制用户使用
WRITE
权限的情况下返回该目录?
If you want to avoid the hard coded string, you could try to use reflect. 如果要避免使用硬编码字符串,可以尝试使用反射。
Class<?> environmentClass = Environment.class;
try {
Field androidDirectoryField = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
androidDirectoryField = environmentClass.getDeclaredField("DIR_ANDROID");
} else {
androidDirectoryField = environmentClass.getDeclaredField("DIRECTORY_ANDROID");
}
androidDirectoryField.setAccessible(true);
final String externalDir = Environment.getExternalStorageDirectory().getAbsolutePath()
+ getFilesDir().getAbsolutePath().replaceFirst("data", androidDirectoryField.get(null).toString());
Log.d(TAG, "external directory " + externalDir);
} catch (NoSuchFieldException | IllegalAccessException | IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.