Android 意图打开图片库,但不是图片。为什么?
Android intent opens picture gallery, but not picture. Why?
我的应用程序中有几张图片,我想在用户点击它们时在默认查看器中打开它们。这是我的代码:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file://" + Environment.getExternalStorageDirectory().toString() + "/Pictures/mypic.jpg");
intent.setData(uri);
intent.setType("image/jpeg");
startActivity(intent);
默认查看器确实已打开,但显示其 "home screen",显示所有文件夹和画廊。它不显示所选图片。
我做错了什么?
将以下代码放在 try 块中,您可以打开任何文件:
自己添加捕获块。
String FileName = ...full path of file...
MimeTypeMap map = MimeTypeMap.getSingleton();
String extension = map.getFileExtensionFromUrl(FileName.toLowerCase().replace(" ", "")); // does not work with spaces in filename
String mimetype = map.getMimeTypeFromExtension(extension);
Toast.makeText(context, FileName + "\nMimeType: " + mimetype + "\nExtension: " + extension , Toast.LENGTH_SHORT).show();
if ( mimetype == null )
{
mimetype = "text/plain";
Toast.makeText(context, "MimeType: " + mimetype, Toast.LENGTH_SHORT).show();
}
String Url = "file://" + FileName;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(Url), mimetype);
context.startActivity(intent);
我的应用程序中有几张图片,我想在用户点击它们时在默认查看器中打开它们。这是我的代码:
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file://" + Environment.getExternalStorageDirectory().toString() + "/Pictures/mypic.jpg");
intent.setData(uri);
intent.setType("image/jpeg");
startActivity(intent);
默认查看器确实已打开,但显示其 "home screen",显示所有文件夹和画廊。它不显示所选图片。
我做错了什么?
将以下代码放在 try 块中,您可以打开任何文件: 自己添加捕获块。
String FileName = ...full path of file...
MimeTypeMap map = MimeTypeMap.getSingleton();
String extension = map.getFileExtensionFromUrl(FileName.toLowerCase().replace(" ", "")); // does not work with spaces in filename
String mimetype = map.getMimeTypeFromExtension(extension);
Toast.makeText(context, FileName + "\nMimeType: " + mimetype + "\nExtension: " + extension , Toast.LENGTH_SHORT).show();
if ( mimetype == null )
{
mimetype = "text/plain";
Toast.makeText(context, "MimeType: " + mimetype, Toast.LENGTH_SHORT).show();
}
String Url = "file://" + FileName;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(Url), mimetype);
context.startActivity(intent);