intent.setType()...
Type(数据类型)
显示的指定Intent的数据类型,而跳过了通过Uri进行推导判断的步骤。
如:Vedio、Image、Voice等。
intent.setType(“image/*”);
//intent.setType(“audio/*”); //选择音频
//intent.setType(“video/*”); //选择视频 (mp4 3gp 是android支持的视频格式)
例如,我要实现获取手机相册功能可用如下代码:
Intent intent = new Intent(Intent.ACTION_PICK);//intent action属性
intent.setType("image/*");//选择图片
startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
但是setType只支持单个setType
正确的做法(比如我要限制只查看ppt ,doc,docx,pptx,pdf等文件)如下:
public static final String DOC = "application/msword";
public static final String DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
public static final String XLS = "application/vnd.ms-excel application/x-excel";
public static final String XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public static final String PPT = "application/vnd.ms-powerpoint";
public static final String PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
public static final String PDF = "application/pdf";
try {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
//设置doc,docx,ppt,pptx,pdf 5种类型
intent.setType("application/msword|application/vnd.openxmlformats-officedocument.wordprocessingml.document" +
"|application/vnd.ms-powerpoint|application/vnd.openxmlformats-officedocument.presentationml.presentation|application/pdf");
//在API>=19之后设置多个类型采用以下方式,setType不再支持多个类型
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{DOC,DOCX, PPT, PPTX,PDF});
}
startActivityForResult(intent, 1001);
} catch (ActivityNotFoundException e) {
}
常见错误用法:
Intent intent = new Intent("android.intent.action.VIEW");
intent.setData(mUri);
intent.setType("image/*");
intent.putExtra("pictureUrl","file://"+mPath+"/girl.jpg");
startActivity(intent);
会出现:Intent.getData()方法返回值为空
因为:setType的时候把data置空了, setData的时候把type置空了
public Intent setData(Uri data) {
mData = data;
mType = null;
return this;
}
public Intent setType(String type) {
mData = null;
mType = type;
return this;
}
解决:
一定要使用setDataAndType方法,才可以将两个值一起传入:
intent.setDataAndType(mUri,"image/*");