在我的应用中,我想为用户提供一种从应用的数据目录中选择文件的方法。这是我的代码:
// use ACTION_OPEN_DOCUMENT because ACTION_GET_CONTENT will give us
// gallery and other stuff we don’t need
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
Uri uri = Uri.parse(getExternalFilesDir(null).getAbsolutePath());
Log.d(TAG, "Browsing " + uri.toString());
intent.setDataAndType(uri, "*/*");
// show the entire internal storage tree
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
startActivityForResult(intent, 42);
日志记录器显示我正在设置的URI为file:///sdcard/Android/data/my.app/files
,但是文件选择器UI默认为共享存储根(/sdcard
)。
以下代码有效(根据文档要求使用API 26+,该意图可以从DocumentsContract.EXTRA_INITIAL_URI
的API获得):
// works only with this intent, at the expense of gallery etc. appearing
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// apparently we need a valid content URI
Uri uri = Uri.parse("content://com.android.externalstorage.documents/document/primary%3AAndroid%2Fdata%2Fmy.app%2Ffiles");
intent.putExtra("android.provider.extra.INITIAL_URI", uri);
Log.d(TAG, "Browsing " + uri.toString());
intent.setType("*/*");
// show the entire internal storage tree
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
startActivityForResult(intent, 42);
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uri);
但是,当我需要的只是本地文件系统(实际上只是应用程序的私有子树)时,ACTION_GET_CONTENT
会导致出现各种类型的提供程序,例如Gallery和Music。如果我将意图更改为ACTION_OPEN_DOCUMENT
,则会忽略我提供的URI。
如何才能使文件选择器UI从我选择的目录中启动,而只有很少的内容提供者选择?
编辑:我刚刚意识到只有在API 25上才能在Anbox上进行测试,实际上,我需要一种可在24级以下的API上运行的方法。