所以我正在编写一个意图,它应该启动图库以查看通过 Uri 传递到意图的图像。这段代码运行良好,完全符合我的要求:
private Intent makeGalleryIntent(String pathToImageFile) {
Intent mGalleryIntent = new Intent(Intent.ACTION_VIEW);
mGalleryIntent.setDataAndType(Uri.parse("file://" + pathToImageFile), "image/*");
return mGalleryIntent;
}
但是当我尝试使用它时(只是在学习时尝试不同的东西),此代码要么在模拟器上崩溃,因为它无法启动相机,要么只是在我的物理设备上拉出我的画廊:
private Intent makeGalleryIntent(String pathToImageFile) {
Intent mGalleryIntent = new Intent(Intent.ACTION_VIEW);
mGalleryIntent.setData(Uri.parse("file://" + pathToImageFile));
mGalleryIntent.setType("image/*");
return mGalleryIntent;
}
他们看起来都应该做同样的事情。另外,有没有一种方法可以仅使用 Intent 构造函数正确设置所有这些?
最佳答案
来自文档:Intent Documentation
To set only the data URI, call setData(). To set only the MIME type, call setType(). If necessary, you can set both explicitly with setDataAndType().
Caution: If you want to set both the URI and MIME type, do not call setData() and setType() because they each nullify the value of the other. Always use setDataAndType() to set both URI and MIME type.
我从来没有真正得到过他们为什么会互相抵消的答案。如果你知道为什么我喜欢听到它!
关于android-intent - Android Intents - SetDataAndType 与 setData 和 setType 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29507843/