打开系统文件:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult(Intent.createChooser(intent, getString(R.string.im_text_select_file)), SEND_NORMAL_FILE); } catch (android.content.ActivityNotFoundException ex) { BAUtil.showToast(this, "未找到文件管理应用,请安装文件管理应用后再试"); }
回调方法:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case SEND_NORMAL_FILE: try { String path = ""; if (Build.VERSION.SDK_INT >= 19) { path = handleImageOnKitKat(context, data); } else { path = handleImageBeforeKitKat(context, data); } doSendNormalFile(path, BAAttach.TYPE_FILE); } catch (Exception e) { e.printStackTrace(); } break;}}
@TargetApi(Build.VERSION_CODES.KITKAT) public static String handleImageOnKitKat(Context context, Intent data) { Uri uri = data.getData(); if (DocumentsContract.isDocumentUri(context, uri)) { String docId = DocumentsContract.getDocumentId(uri); if ("com.android.providers.media.documents".equals(uri.getAuthority())) { String id = docId.split(":")[1]; String selection = MediaStore.Images.Media._ID + "=" + id; String type = docId.split(":")[0]; Uri contentUri = null; if (type.equalsIgnoreCase("image")) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if (type.equalsIgnoreCase("audio")) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } else if (type.equalsIgnoreCase("video")) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } return getImagePath(context, contentUri, selection); } else if ("com.android.providers.media.downloads.documents".equals(uri.getAuthority())) { Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId)); return getImagePath(context, contentUri, null); } else if ("content".equals(uri.getAuthority())) { return getImagePath(context, uri, null); } else if ("file".equals(uri.getAuthority())) { return uri.getPath(); } } return ""; } public static String handleImageBeforeKitKat(Context context, Intent data) { Uri uri = data.getData(); return getImagePath(context, uri, null); } private static String getImagePath(Context context, Uri uri, String selection) { String path = null; Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null); if (cursor != null) { if (cursor.moveToFirst()) { path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); } cursor.close(); } return path; }