zxg*_*ear 32 android file-permissions
我目前正在构建一个文件管理应用程序,允许用户浏览其设备的文件系统.用户/从其设备的根目录开始,但可以浏览到他们想要的任何位置,例如内部闪存或SD卡.
此应用程序的一个关键要求是允许用户在任何地方创建新文件夹.像这样的功能对应用程序非常有用.但是,该File#mkdir()方法在SD卡目录中根本不起作用.
我为清单文件添加了适当的权限.我还写了一个测试,看看哪些目录(我的Lollipop 5.0设备上都存在)允许创建一个新文件夹.根据我的观察,File#mkdir()只有在内部闪存目录中才有效.
注意:请不要Environment#getExternalStorageDirectory()与SD卡位置混淆,如本文所述.同样在Lollipop 5.0上,我相信/storage/emulated/0/并/storage/sdcard0/参考内部闪存存储,/storage/emulated/1/并/storage/sdcard1/参考SD卡(至少对我正在测试的设备是真的).
如何在非root用户Android设备上的外部存储路径之外的区域中创建新文件和文件夹?
表现:
...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
Run Code Online (Sandbox Code Playgroud)
测试:
...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String NEW_FOLDER_NAME = "TestFolder";
testPath(new File(Environment.getExternalStorageDirectory(), NEW_FOLDER_NAME));
testPath(new File("/storage/emulated/0/", NEW_FOLDER_NAME));
testPath(new File("/storage/emulated/1/", NEW_FOLDER_NAME));
testPath(new File("/storage/sdcard0/Download/", NEW_FOLDER_NAME));
testPath(new File("/storage/sdcard1/Pictures/", NEW_FOLDER_NAME));
}
private void testPath(File path) {
String TAG = "Debug.MainActivity.java";
String FOLDER_CREATION_SUCCESS = " mkdir() success: ";
boolean success = path.mkdir();
Log.d(TAG, path.getAbsolutePath() + FOLDER_CREATION_SUCCESS + success);
path.delete();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
/storage/emulated/0/TestFolder mkdir() success: true
/storage/emulated/0/TestFolder mkdir() success: true
/storage/emulated/1/TestFolder mkdir() success: false
/storage/sdcard0/Download/TestFolder mkdir() success: true
/storage/sdcard1/Pictures/TestFolder mkdir() success: false
Run Code Online (Sandbox Code Playgroud)
Jar*_*ler 23
首先,您应该注意file.mkdir()并且如果目录已经存在则file.mkdirs()返回false.如果要在返回时知道目录是否存在,请使用(file.mkdir() || file.isDirectory())或只是忽略返回值并调用file.isDirectory()(请参阅文档).
也就是说,您真正的问题是您需要在Android 5.0+上的可移动存储上创建目录的权限.在Android上使用可移动SD卡是可怕的.
在Android 4.4(KitKat)上,Google限制访问SD卡(请参阅此处,此处和此处).如果您需要在Android 4.4(KitKat)上的可移动SD卡上创建目录,请参阅此StackOverflow答案,该答案会导致此XDA帖子.
在Android 5.0(Lollipop)上,谷歌推出了新的SD卡访问API.有关示例用法,请参阅此stackoverflow答案.
基本上,您需要使用DocumentFile#createDirectory(String displayName)来创建目录.在创建此目录之前,您需要要求用户向您的应用授予权限.
注意:这适用于可移动存储.File#mkdirs()如果您拥有该权限,则使用将用于内部存储(通常与Android上的外部存储混淆)android.permission.WRITE_EXTERNAL_STORAGE.
我将在下面发布一些示例代码:
检查您是否需要征得许可:
File sdcard = ... // the removable SD card
List<UriPermission> permissions = context.getContentResolver().getPersistedUriPermissions();
DocumentFile documentFile = null;
boolean needPermissions = true;
for (UriPermission permission : permissions) {
if (permission.isWritePermission()) {
documentFile = DocumentFile.fromTreeUri(context, permission.getUri());
if (documentFile != null) {
if (documentFile.lastModified() == sdcard.lastModified()) {
needPermissions = false;
break;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
接下来(如果needPermissions是true),您可以显示一个对话框,向用户解释他们需要选择"SD卡"以授予您的应用创建文件/目录的权限,然后启动以下活动:
if (needPermissions) {
// show a dialog explaining that you need permission to create the directory
// here, we will just launch to chooser (what you need to do after showing the dialog)
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), STORAGE_REQUEST_CODE);
} else {
// we already have permission to write to the removable SD card
// use DocumentFile#createDirectory
}
Run Code Online (Sandbox Code Playgroud)
您现在需要检查resultCode并requestCode在onActivityResult:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == STORAGE_REQUEST_CODE && resultCode == RESULT_OK) {
File sdcard = ... // get the removable SD card
boolean needPermissions = true;
DocumentFile documentFile = DocumentFile.fromTreeUri(MainActivity.this, data.getData());
if (documentFile != null) {
if (documentFile.lastModified() == sdcard.lastModified()) {
needPermissions = false;
}
}
if (needPermissions) {
// The user didn't select the "SD Card".
// You should try the process over again or do something else.
} else {
// remember this permission grant so we don't need to ask again.
getContentResolver().takePersistableUriPermission(data.getData(),
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Now we can work with DocumentFile and create our directory
DocumentFile doc = DocumentFile.fromTreeUri(this, data.getData());
// do stuff...
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
Run Code Online (Sandbox Code Playgroud)
这应该会为您DocumentFile在Android 5.0+ 上使用和移动SD卡提供良好的开端.它可以是PITA.
此外,没有公共API来获取可移动SD卡的路径(如果存在的话).你不应该依赖硬编码"/storage/sdcard1"!StackOverflow上有很多关于它的帖子.许多解决方案都使用环境变量SECONDARY_STORAGE.以下是可用于查找可移动存储设备的两种方法:
public static List<File> getRemovabeStorages(Context context) throws Exception {
List<File> storages = new ArrayList<>();
Method getService = Class.forName("android.os.ServiceManager")
.getDeclaredMethod("getService", String.class);
if (!getService.isAccessible()) getService.setAccessible(true);
IBinder service = (IBinder) getService.invoke(null, "mount");
Method asInterface = Class.forName("android.os.storage.IMountService$Stub")
.getDeclaredMethod("asInterface", IBinder.class);
if (!asInterface.isAccessible()) asInterface.setAccessible(true);
Object mountService = asInterface.invoke(null, service);
Object[] storageVolumes;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String packageName = context.getPackageName();
int uid = context.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.uid;
Method getVolumeList = mountService.getClass().getDeclaredMethod(
"getVolumeList", int.class, String.class, int.class);
if (!getVolumeList.isAccessible()) getVolumeList.setAccessible(true);
storageVolumes = (Object[]) getVolumeList.invoke(mountService, uid, packageName, 0);
} else {
Method getVolumeList = mountService.getClass().getDeclaredMethod("getVolumeList");
if (!getVolumeList.isAccessible()) getVolumeList.setAccessible(true);
storageVolumes = (Object[]) getVolumeList.invoke(mountService, (Object[]) null);
}
for (Object storageVolume : storageVolumes) {
Class<?> cls = storageVolume.getClass();
Method isRemovable = cls.getDeclaredMethod("isRemovable");
if (!isRemovable.isAccessible()) isRemovable.setAccessible(true);
if ((boolean) isRemovable.invoke(storageVolume, (Object[]) null)) {
Method getState = cls.getDeclaredMethod("getState");
if (!getState.isAccessible()) getState.setAccessible(true);
String state = (String) getState.invoke(storageVolume, (Object[]) null);
if (state.equals("mounted")) {
Method getPath = cls.getDeclaredMethod("getPath");
if (!getPath.isAccessible()) getPath.setAccessible(true);
String path = (String) getPath.invoke(storageVolume, (Object[]) null);
storages.add(new File(path));
}
}
}
return storages;
}
public static File getRemovabeStorageDir(Context context) {
try {
List<File> storages = getRemovabeStorages(context);
if (!storages.isEmpty()) {
return storages.get(0);
}
} catch (Exception ignored) {
}
final String SECONDARY_STORAGE = System.getenv("SECONDARY_STORAGE");
if (SECONDARY_STORAGE != null) {
return new File(SECONDARY_STORAGE.split(":")[0]);
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2779 次 |
| 最近记录: |