标签:
Activity
/**详见http://blog.csdn.net/coder_pig/article/details/47905881Calendar Provider:日历提供者,就是针对针对日历相关事件的一个资源库,通过他提供的API,我们可以对日历,时间,会议,提醒等内容做一些增删改查!Contacts Provider:联系人提供者,这个就不用说了,这个用得最多Storage Access Framework(SAF):存储访问框架,4.4以后引入的一个新玩意,为用户浏览手机中的存储内容提供了便利。可供访问的内容不仅包括:文档,图片,视频,音频,下载,而且包含所有由特定ContentProvider(须具有约定的API)提供的内容。不管这些内容来自于哪里,不管是哪个应用调用浏览系统文件内容的命令,系统都会用一个统一的界面让你去浏览。其实就是一个内置的应用程序,叫做DocumentsUI,因为它的IntentFilter不带有LAUNCHER,所以我们不能在桌面上找到这个东东!*/public class MainActivity extends ListActivity {private TextView tv_info;private static final int READ_REQUEST_CODE = 42;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);List<String> mData = new ArrayList<String>(Arrays.asList("获取一张图片的Uri及Path", "", "", "", ""));ListAdapter mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mData);tv_info = new TextView(this);// 将内容显示在TextView中tv_info.setTextColor(Color.BLUE);tv_info.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);tv_info.setPadding(20, 10, 20, 10);getListView().addFooterView(tv_info);setListAdapter(mAdapter);}@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) {switch (position) {case 0:Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);//Field requires API level 19intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("image/*");startActivityForResult(intent, READ_REQUEST_CODE);break;case 1:break;case 2:break;case 3:break;case 4:break;}}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {if (data != null) {Uri uri = data.getData();Log.i("bqt", "Uri: " + uri.toString() + "\nPath: " + UriPathUtils.getPath(this, uri));tv_info.setText("Uri: " + uri.toString() + "\nPath: " + UriPathUtils.getPath(this, uri));// 4.4之前:Uri: content://com.android.externalstorage.documents/document/primary%3A1.png。Path: /storage/emulated/0/1.png// 4.4之后:Uri: content://com.android.providers.media.documents/document/image%3A16025。 Path: /storage/emulated/0/very_big.jpg}}}}
UriPathUtils
public class UriPathUtils {/**获取Uri对应的文件的路径。 4.4之后需增加权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />*/public static String getPath(Context context, Uri uri) {boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;//19if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // 【DocumentProvider】if (isExternalStorageDocument(uri)) { // 【ExternalStorageProvider】String docId = DocumentsContract.getDocumentId(uri);String[] split = docId.split(":");String type = split[0];if ("primary".equalsIgnoreCase(type)) return Environment.getExternalStorageDirectory() + "/" + split[1];} else if (isDownloadsDocument(uri)) { // 【DownloadsProvider】String id = DocumentsContract.getDocumentId(uri);Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));return getDataColumn(context, contentUri, null, null);} else if (isMediaDocument(uri)) { // 【MediaProvider】String docId = DocumentsContract.getDocumentId(uri);String[] split = docId.split(":");String type = split[0];Uri contentUri = null;if ("image".equals(type)) contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;else if ("video".equals(type)) contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;else if ("audio".equals(type)) contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;String selection = "_id=?";String[] selectionArgs = new String[] { split[1] };return getDataColumn(context, contentUri, selection, selectionArgs);}} else if ("content".equalsIgnoreCase(uri.getScheme())) { // 【MediaStore (and general)】return getDataColumn(context, uri, null, null);} else if ("file".equalsIgnoreCase(uri.getScheme())) { // 【File】return uri.getPath();}return null;}/*** Get the value of the data column for this Uri. This is useful for MediaStore Uris, and other file-based ContentProviders.* @param context The context.* @param uri The Uri to query.* @param selection (Optional) Filter used in the query.* @param selectionArgs (Optional) Selection arguments used in the query.* @return The value of the _data column, which is typically a file path.*/public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {Cursor cursor = null;String column = "_data";String[] projection = { column };try {cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);if (cursor != null && cursor.moveToFirst()) {int column_index = cursor.getColumnIndexOrThrow(column);return cursor.getString(column_index);}} finally {if (cursor != null) cursor.close();}return null;}/*** @param uri The Uri to check.* @return Whether the Uri authority is ExternalStorageProvider.*/public static boolean isExternalStorageDocument(Uri uri) {return "com.android.externalstorage.documents".equals(uri.getAuthority());}/*** @param uri The Uri to check.* @return Whether the Uri authority is DownloadsProvider.*/public static boolean isDownloadsDocument(Uri uri) {return "com.android.providers.downloads.documents".equals(uri.getAuthority());}/*** @param uri The Uri to check.* @return Whether the Uri authority is MediaProvider.*/public static boolean isMediaDocument(Uri uri) {return "com.android.providers.media.documents".equals(uri.getAuthority());}}
UriUtils
public class UriUtils {private static final int WRITE_REQUEST_CODE = 43;/**根据uri获取文件参数*/public static void dumpImageMetaData(Context context, Uri uri) {Cursor cursor = context.getContentResolver().query(uri, null, null, null, null, null);try {if (cursor != null && cursor.moveToFirst()) {String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));Log.e("HeHe", "Display Name: " + displayName);int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);String size = null;if (!cursor.isNull(sizeIndex)) {size = cursor.getString(sizeIndex);} else {size = "Unknown";}Log.e("HeHe", "Size: " + size);}} finally {cursor.close();}}/**根据Uri获得Bitmap*/public static Bitmap getBitmapFromUri(Context context, Uri uri) throws IOException {ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);parcelFileDescriptor.close();return image;}/** 根据Uri获取输入流 */public static String readTextFromUri(Context context, Uri uri) throws IOException {InputStream inputStream = context.getContentResolver().openInputStream(uri);BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));StringBuilder stringBuilder = new StringBuilder();String line;while ((line = reader.readLine()) != null) {stringBuilder.append(line);}inputStream.close();reader.close();return stringBuilder.toString();}/** 创建文件,可在onActivityResult()中获取被创建文件的uri */public static void createFile(Activity context, String mimeType, String fileName) {Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType(mimeType);intent.putExtra(Intent.EXTRA_TITLE, fileName);context.startActivityForResult(intent, WRITE_REQUEST_CODE);}}
标签:
原文地址:http://www.cnblogs.com/baiqiantao/p/5535837.html