//新建intent对象,参数为调用系统的文件管理系统。
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Filter to show only images, using the image MIME data type.
// If one wanted to search for ogg vorbis files, the type would be "audio/ogg".
// To search for all documents available via installed storage providers, it would be
// 这里可以设置要显示的文件的类型,用MIME data tpe的规范来设置,常见的类型可以看这个网页:
//https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
//设置为*/*表示可打开所有文件。只显示pdf的话可以设置为application/pdf
intent.setType("*/*");
//上传类型 'pdf','doc','docx','ppt','pptx','xls','xlsx','txt'
//要设置多种类型可打开,则需要用putExtra。
intent.putExtra(Intent.EXTRA_MIME_TYPES,
new String[]{
"audio/*",
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/vnd.ms-exce",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"text/plain"
});
startActivityForResult(intent, READ_REQUEST_CODE);
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {//用请求码过滤一下我们所需要的互动请求,并验证操作是否成功。
// 用户所点选的文件将以URI地址方式回传,要对这个URI地址进行处理。
// A URI to the document selected by the user document will be contained in the return intent
// provided to this method as a parameter. Pull that uri using "resultData.getData()"
if (resultData != null) {
//获取回传的文件URI地址。以下两行代码是对所获取到的pdf进行处理并用RecyclerView显示到界面上,具体可以看前两篇blog的介绍。
// filePathUri=resultData.getData();
Log.i("sqd",resultData.getData().toString());
//查询文件名和文件类型
DocumentFile documentFile = DocumentFile.fromSingleUri(getContext(),filePathUri);
if(documentFile.canRead()){
Log.i("sqd", documentFile.getName());
Log.i("sqd", documentFile.getType());
documentFile.getName();
documentFile.getType();
}
}
}