笔者在尝试用手机上已安装的应用打开手机上的某个文件时,写了如下代码:
String path = Environment.getExternalStorageDirectory() + "/adb测试/" + "极道追杀.txt";
File file = new File(path);
if (file.exists()){
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
System.out.println(bufferedReader.readLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
intent.setType("text/plain");
startActivity(intent);
} else {
Toast.makeText(this,"文件不存在",Toast.LENGTH_SHORT).show();
}
结果在调用这段代码的时候,能显示能打开这个文件的列表,但是跳转后文件为空
![](https://img.haomeiwen.com/i11069961/24972a8614e84ba4.jpeg)
命名设置过了uri,为什么还会为空呢?
但在我把代码改成:
...
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri,"text/plain");
startActivity(intent);
...
这样子就能成功打开文件了。
![](https://img.haomeiwen.com/i11069961/ececf8894e5be3e7.jpg)
这么神奇的问题,还是看源码吧。
先看看传入Action和Uri的Intent构造函数:
public Intent(String action, Uri uri) {
setAction(action);
mData = uri;
}
好的,把uri存入mData中了,没毛病。
那坑只能是setType了:
public @NonNull Intent setType(@Nullable String type) {
mData = null;
mType = type;
return this;
}
果
不
其
然
setType里把mData设置为null了,想来是为了避免数据类型改变了传的数据没变这种不匹配的情况。
![](https://img.haomeiwen.com/i11069961/737ecabdfabc4852.jpg)
嗯,所以,要先设置类型再传入uri,不然穿了也没用
网友评论