android-intent - Android Intents - SetDataAndType 与 setData 和 setType 之间的区别?

标签 android-intent

所以我正在编写一个意图,它应该启动图库以查看通过 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/

相关文章:

android - 广播接收器仅在 Activity 运行时才激活,否则停用

android - onitemclick 在 ListView 对话框中不起作用

android - 从 Android 中的 Activity 启动服务时出现 "Unable to start service Intent"错误

java - 在 Android 中打开文件

android-intent - Android Activity 需要 3 秒才能显示

android - 如何了解 Android 中的标准应用程序?

android - 将 uri.parse 资源设置为 ImageView

android-layout - 为什么我的 Android setOnItemClickListener 不起作用?

android - 在 Android 中以编程方式设置 APN

android - 以编程方式发送 SMS Android(未接收状态)