android – 从真正的路径获取Uri

前端之家收集整理的这篇文章主要介绍了android – 从真正的路径获取Uri前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个文件的真实路径,如“file:///mnt/sdcard/3dphoto/temp19.jps”
,我怎么能得到像“content:// media / external / images / media / 1”这样的uri?

解决方法

文件路径中转换“file:// …”,使用以下代码查找项目的ID,然后将其附加到提供者URI.此外,基于文件扩展名,使用正确的提供程序(例如MediaStore.Video.Media.EXTERNAL_CONTENT_URI或MediaStore. Image.Media.EXTERNAL_CONTENT_URI)
  1. /**
  2. * Given a media filename,returns it's id in the media content provider
  3. *
  4. * @param providerUri
  5. * @param appContext
  6. * @param fileName
  7. * @return
  8. */
  9. public long getMediaItemIdFromProvider(Uri providerUri,Context appContext,String fileName) {
  10. //find id of the media provider item based on filename
  11. String[] projection = { MediaColumns._ID,MediaColumns.DATA };
  12. Cursor cursor = appContext.getContentResolver().query(
  13. providerUri,projection,MediaColumns.DATA + "=?",new String[] { fileName },null);
  14. if (null == cursor) {
  15. Log.d(TAG_LOG,"Null cursor for file " + fileName);
  16. return ITEMID_NOT_FOUND;
  17. }
  18. long id = ITEMID_NOT_FOUND;
  19. if (cursor.getCount() > 0) {
  20. cursor.moveToFirst();
  21. id = cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID));
  22. }
  23. cursor.close();
  24. return id;
  25. }

有时,在将一个媒体文件添加到设备的存储中后,MediaProvider不会立即刷新.您可以使用此方法强制刷新其记录:

  1. /**
  2. * Force a refresh of media content provider for specific item
  3. *
  4. * @param fileName
  5. */
  6. private void refreshMediaProvider(Context appContext,String fileName) {
  7. MediaScannerConnection scanner = null;
  8. try {
  9. scanner = new MediaScannerConnection(appContext,null);
  10. scanner.connect();
  11. try {
  12. Thread.sleep(200);
  13. } catch (Exception e) {
  14. }
  15. if (scanner.isConnected()) {
  16. Log.d(TAG_LOG,"Requesting scan for file " + fileName);
  17. scanner.scanFile(fileName,null);
  18. }
  19. } catch (Exception e) {
  20. Log.e(TAG_LOG,"Cannot to scan file",e);
  21. } finally {
  22. if (scanner != null) {
  23. scanner.disconnect();
  24. }
  25. }
  26. }

猜你在找的Android相关文章