与定义扩展的Android浏览文件意图 [英] android browse file intent with defined extension
本文介绍了与定义扩展的Android浏览文件意图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要创建的意图,将打开文件管理器(如有安装),我希望文件管理器只显示txt文件到用户,所以用户无法选择使用错误的扩展文件。
私有静态最终诠释FILE_SELECT_ code = 0;私人无效showFileChooser(){
意向意图=新意图(Intent.ACTION_GET_CONTENT);
intent.setType(* / *);
intent.addCategory(Intent.CATEGORY_OPENABLE);
尝试{
startActivityForResult(
Intent.createChooser(意向,选择txt文件),
FILE_SELECT_ code);
}赶上(android.content.ActivityNotFoundException前){
//直接潜在用户市场提供一个对话
Toast.makeText(this.getActivity(),请安装一个文件管理器。
Toast.LENGTH_SHORT).show();
}
}公共无效的onActivityResult(INT申请code,INT结果code,意图数据){
开关(要求code){
案例FILE_SELECT_ code:
如果(结果code == Activity.RESULT_OK){
//获取所选文件的URI
URI URI = data.getData();
字符串路径= uri.getPath();
输入=新的文件(路径);
尝试{
txtParser =新TxtFileParser(输入);
}赶上(FileNotFoundException异常五){
/ *异常处理程序必须在这里! * /
}
}
打破;
}
super.onActivityResult(要求code,结果code,数据);
}
我设法做到这一点。但我不知道如何定义TXT扩展。
解决方案
我希望文件管理器只显示txt文件到用户,所以用户不能选择带有扩展名错误文件
块引用>确实没有可能的。欢迎您使用MIME类型
文本/纯
而不是* / *
,但
- 谁也不能保证,这将只是一个
.TXT
扩展返回文件- 没有保证,有能够处理
设备上的任何应用程序ACTION_GET_CONTENT
的MIME类型- 谁也不能保证任何的文件管理器将尊重您的MIME类型;他们可以选择反正显示所有文件
I need to create intent that will open file manager (if any installed) and I want file manager to show only txt files to user, so user couldn't choose file with wrong extension.
private static final int FILE_SELECT_CODE = 0; private void showFileChooser() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult( Intent.createChooser(intent, "Select txt file"), FILE_SELECT_CODE); } catch (android.content.ActivityNotFoundException ex) { // Potentially direct the user to the Market with a Dialog Toast.makeText(this.getActivity(), "Please install a File Manager.", Toast.LENGTH_SHORT).show(); } } public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case FILE_SELECT_CODE: if (resultCode == Activity.RESULT_OK) { // Get the Uri of the selected file Uri uri = data.getData(); String path = uri.getPath(); input = new File(path); try { txtParser = new TxtFileParser(input); } catch (FileNotFoundException e) { /* Exception handler must be here! */ } } break; } super.onActivityResult(requestCode, resultCode, data); }
I managed to do this. But I don't know how to define txt extensions.
解决方案I want file manager to show only txt files to user, so user couldn't choose file with wrong extension
That is not literally possible. You are welcome to use a MIME type of
text/plain
instead of*/*
, but:
- There is no guarantee that this will only return files with a
.txt
extension- There is no guarantee that there is any app on the device that can handle
ACTION_GET_CONTENT
of that MIME type- There is no guarantee that any "file manager" will honor your MIME type; they may elect to display all files anyway
这篇关于与定义扩展的Android浏览文件意图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文