点击“从SD卡上传”选项后
Intent intentFromGallery = new Intent();
intentFromGallery.setType("*/*");
//intentFromGallery.setType("image/*,audio/*,video/*,text/plain,application/msword");//mime
intentFromGallery.addCategory(Intent.CATEGORY_OPENABLE);
intentFromGallery.setAction(android.content.Intent.ACTION_GET_CONTENT);
try {
startActivityForResult(Intent.createChooser(intentFromGallery, "请选择一个要上传的文件"),
111);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(getApplicationContext(), "请安装文件管理器", Toast.LENGTH_SHORT)
.show();
}
然后在onActivityResult()中
if(requestCode == 111 && resultCode == RESULT_OK){
File sdFile = null;
try {
Uri uri = data.getData();
// tempf = new File(new URI(uri.toString()));
String[] proj = {
MediaStore.Images.Media.DATA
}; //_data
Cursor actualimagecursor = this.managedQuery(uri, proj, null, null, null);
if (actualimagecursor == null) {
ToastUtils.showToast(getApplicationContext(), "不支持该类型");
return;
}
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path = actualimagecursor.getString(actual_image_column_index); //字段索引
sdFile = new File(img_path);
// Uri fileUri = Uri.fromFile(file);
} catch(Exception e) {
e.printStackTrace();
}
这样就得到了文件 sdFile,然后随便做什么后续处理
比如 显示不同类型文件图标
if (sdFile != null) {
int start = sdFile.getPath().lastIndexOf("/");
String imgName = sdFile.getPath().substring(start + 1);
DisplayAndFileBean displayAndFileBean = new DisplayAndFileBean();
//显示图标
String typeStr = imgName.substring(imgName.lastIndexOf("."), imgName.length()).toLowerCase();
if (typeStr.contains(".m4a") || typeStr.contains(".mp3") || typeStr.contains(".mid") || typeStr.contains(".xmf") || typeStr.contains(".ogg") || typeStr.contains(".wav") || typeStr.contains(".amr")) {
displayAndFileBean.setImageStr(mediaPhotographPath);
} else if (typeStr.contains(".mp4") || typeStr.contains(".3gp") || typeStr.contains(".rm") || typeStr.contains(".avi") || typeStr.contains(".rmvb")) {
displayAndFileBean.setImageStr(videoPhotographPath);
} else if (imgName.contains("temp_photograph.png")) {
displayAndFileBean.setImageStr(photographPath);
} else {
if (typeStr.contains("jpg") || typeStr.contains("gif") || typeStr.contains("png") || typeStr.contains("jpeg") || typeStr.contains("bmp")) {
displayAndFileBean.setImageStr(sdFile.getPath());
} else {
displayAndFileBean.setImageStr(otherfilePhotographPath);
}
}
当然显示图标有更好的做法,参考 checkEndsWithInStringArray(String checkItsEnd,String[] fileEndings)方法