Android 如何使Itent.ACTION\u SEND适用于任何文件类型
我使用以下代码片段打开或共享设备存储器中的任何文件(Android 如何使Itent.ACTION\u SEND适用于任何文件类型,android,android-intent,Android,Android Intent,我使用以下代码片段打开或共享设备存储器中的任何文件(MyFile是我自己的类,它扩展了file,应该被视为file。我传递的标志String是Intent。ACTION\u VIEW或Intent\u ACTION\u SEND): 在传递Intent.ACTION\u视图时,系统会创建一个选择器并列出应用程序,对于已知文件,系统会启动正确的活动以立即处理文件 问题:传递Intent.ACTION\u SEND似乎起到了一半的作用-它也创建了选择器,但是大多数应用程序(Dropbox和我测试过的
MyFile
是我自己的类,它扩展了file
,应该被视为file
。我传递的标志String
是Intent。ACTION\u VIEW
或Intent\u ACTION\u SEND
):
在传递Intent.ACTION\u视图时,系统会创建一个选择器并列出应用程序,对于已知文件,系统会启动正确的活动
以立即处理文件
问题:传递Intent.ACTION\u SEND
似乎起到了一半的作用-它也创建了选择器,但是大多数应用程序(Dropbox和我测试过的许多应用程序)在确认操作时都会因NPE而崩溃。对各种电子邮件客户端的测试也失败了:它们不像大多数其他应用程序那样崩溃,而是创建一条消息,并将本地Uri
(如//storage/..
)放在To
字段(gmail)中,或者干脆创建一条新的空消息,忽略意图
数据(yahoo!mail),而我希望他们将文件附加到新邮件
问题:我在共享任何文件类型时做错了什么
编辑
我发现如果使用intent.putExtra(intent.EXTRA_STREAM,Uri.fromFile(f)),它是有效的
,但是在尝试共享某些特定文件(如.dat)时,会捕获到一个ActivityNotFoundException
。据我所知,Dropbox等应用程序支持添加任何文件类型。正在寻找解决方法。如果不知道文件的MIME类型,请不要设置它
因此,我会尝试:
Intent intent = new Intent(flag);
Uri data = Uri.fromFile(f);
String ftype = mmap.getMimeTypeFromExtension(type);
if (ftype != null) {
intent.setDataAndType(data, ftype);
} else {
intent.setData(data);
}
需要数据和显式mime类型(可能*/*不是)。没关系,我终于找到了答案。下面是一个可行的解决方案,它允许使用任何应用程序共享任何类型的数据*:
*注意:下面的代码实际上还列出了可能无法处理特定文件类型的应用程序,这些应用程序(至少应该)会通知用户,如果是这种情况,则不支持该文件类型
Intent intent = new Intent(flag);
Uri data = Uri.fromFile(f);
String ftype = mmap.getMimeTypeFromExtension(type);
if (ftype != null) {
intent.setDataAndType(data, ftype);
} else {
intent.setData(data);
}
public void doShare(MyFile f) {
try {
Intent intent = new Intent(Intent.ACTION_SEND);
MimeTypeMap mmap = MimeTypeMap.getSingleton();
String type = MimeTypeMap.getFileExtensionFromUrl(f.getName());
String ftype = mmap.getMimeTypeFromExtension(type);
if (ftype == null)
ftype = "*/*";
intent.setType(ftype);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
Tools.gimmeToast(getActivity(),
"no application found to handle this file type",
Toast.LENGTH_LONG);
} catch (Exception e) {
e.printStackTrace();
}
}