public static Uri getUriFromFile(final String path, Context context) {
    ContentResolver resolver = context.getContentResolver();

    Cursor filecursor =
        resolver.query(
            MediaStore.Files.getContentUri("external"),
            new String[] {BaseColumns._ID},
            MediaStore.MediaColumns.DATA + " = ?",
            new String[] {path},
            MediaStore.MediaColumns.DATE_ADDED + " desc");
    filecursor.moveToFirst();

    if (filecursor.isAfterLast()) {
      filecursor.close();
      ContentValues values = new ContentValues();
      values.put(MediaStore.MediaColumns.DATA, path);
      return resolver.insert(MediaStore.Files.getContentUri("external"), values);
    } else {
      int imageId = filecursor.getInt(filecursor.getColumnIndex(BaseColumns._ID));
      Uri uri =
          MediaStore.Files.getContentUri("external")
              .buildUpon()
              .appendPath(Integer.toString(imageId))
              .build();
      filecursor.close();
      return uri;
    }
  }
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    String[] projection = {MediaStore.Files.FileColumns.DATA};

    String selection =
        MediaStore.Files.FileColumns.MEDIA_TYPE
            + "="
            + MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
            + " OR "
            + MediaStore.Files.FileColumns.MEDIA_TYPE
            + "="
            + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;

    Cursor cursor =
        getActivity()
            .managedQuery(
                MediaStore.Files.getContentUri("external"), projection, selection, null, null);

    cursor.moveToPosition(1);
    String dataIndex = MediaStore.Files.FileColumns.DATA;
    int filePathColumn = cursor.getColumnIndexOrThrow(dataIndex);
    String filePath = cursor.getString(filePathColumn);

    int substrInt = filePath.lastIndexOf("/");
    String actualLocation = "";
    if (substrInt > 0) {
      actualLocation = filePath.substring(0, substrInt + 1);
    }

    String fileName = "TEMP" + ".jpg";
    mFile = new File(actualLocation, fileName);
  }
  @Override
  public void deleteDocument(String docId) throws FileNotFoundException {
    final File file = getFileForDocId(docId);
    final boolean isDirectory = file.isDirectory();
    if (isDirectory) {
      FileUtils.deleteContents(file);
    }
    if (!file.delete()) {
      throw new IllegalStateException("Failed to delete " + file);
    }

    final ContentResolver resolver = getContext().getContentResolver();
    final Uri externalUri = MediaStore.Files.getContentUri("external");

    // Remove media store entries for any files inside this directory, using
    // path prefix match. Logic borrowed from MtpDatabase.
    if (isDirectory) {
      final String path = file.getAbsolutePath() + "/";
      resolver.delete(
          externalUri,
          "_data LIKE ?1 AND lower(substr(_data,1,?2))=lower(?3)",
          new String[] {path + "%", Integer.toString(path.length()), path});
    }

    // Remove media store entry for this exact file.
    final String path = file.getAbsolutePath();
    resolver.delete(
        externalUri, "_data LIKE ?1 AND lower(_data)=lower(?2)", new String[] {path, path});
  }
 private void observerMediaStoreChange() {
   if (null == mMediaStoreChangeObserver) {
     mMediaStoreChangeObserver = new MediaStoreChangeObserver();
   }
   mContext
       .getContentResolver()
       .registerContentObserver(
           MediaStore.Files.getContentUri("external"), false, mMediaStoreChangeObserver);
 }
  /** 从媒体库中获取指定后缀的文件列表 */
  public ArrayList<String> getSupportFileList(Context context, String[] searchFileSuffix) {
    ArrayList<String> searchFileList = null;
    if (null == context || null == searchFileSuffix || searchFileSuffix.length == 0) {
      return null;
    }

    String searchPath = "";
    int length = searchFileSuffix.length;
    for (int index = 0; index < length; index++) {
      searchPath +=
          (MediaStore.Files.FileColumns.DATA + " LIKE '%" + searchFileSuffix[index] + "' ");
      if ((index + 1) < length) {
        searchPath += "or ";
      }
    }

    searchFileList = new ArrayList<String>();
    Uri uri = MediaStore.Files.getContentUri("external");
    Cursor cursor =
        context
            .getContentResolver()
            .query(
                uri,
                new String[] {
                  MediaStore.Files.FileColumns.DATA,
                  MediaStore.Files.FileColumns.SIZE,
                  MediaStore.Files.FileColumns._ID
                },
                searchPath,
                null,
                null);

    String filepath = null;
    if (cursor == null) {
      System.out.println("Cursor 获取失败!");
    } else {
      if (cursor.moveToFirst()) {
        do {
          filepath = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));
          try {
            searchFileList.add(new String(filepath.getBytes("UTF-8")));
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          }

        } while (cursor.moveToNext());
      }

      if (!cursor.isClosed()) {
        cursor.close();
      }
    }

    return searchFileList;
  }
Example #6
0
  @Override
  protected ArrayList<DocsPojo> doInBackground(Void... params) {
    ArrayList<DocsPojo> docs = new ArrayList<>();
    if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
      mimeTypeMap = getMimeTypeMap();

      final String[] DOC_PROJECTION = {
        MediaStore.Images.Media._ID,
        MediaStore.Images.Media.DATA,
        MediaStore.Files.FileColumns.MIME_TYPE,
        MediaStore.Files.FileColumns.SIZE,
        MediaStore.Images.Media.DATE_ADDED,
        MediaStore.Files.FileColumns.TITLE
      };

      Cursor cursor = null;
      try {
        cursor =
            context
                .getContentResolver()
                .query(
                    MediaStore.Files.getContentUri("external"),
                    DOC_PROJECTION,
                    null,
                    null,
                    MediaStore.Files.FileColumns.DATE_ADDED + " DESC");

        if (cursor != null) {
          if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
              String path = cursor.getString(cursor.getColumnIndexOrThrow(DATA));
              String title = cursor.getString(cursor.getColumnIndexOrThrow(TITLE));
              String mimeType = cursor.getString(cursor.getColumnIndexOrThrow(MIME_TYPE));
              if (isKnownMimeType(mimeType)) {
                docs.add(createPojo(title, path, mimeType, R.drawable.ic_doc));
              } else {
                String extension =
                    path.substring(path.lastIndexOf(".") + 1, path.length()); // .doc .pdf
                String extractedMimeType = getMimeType(extension);
                if (extractedMimeType != null)
                  docs.add(createPojo(title, path, extractedMimeType, R.drawable.ic_doc));
              }
            }
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (cursor != null) cursor.close();
      }
    }

    return docs;
  }
 public static InputStream getInputStream(
     final Context context, final File file, final long size) {
   try {
     final String where = MediaStore.MediaColumns.DATA + "=?";
     final String[] selectionArgs = new String[] {file.getAbsolutePath()};
     final ContentResolver contentResolver = context.getContentResolver();
     final Uri filesUri = MediaStore.Files.getContentUri("external");
     contentResolver.delete(filesUri, where, selectionArgs);
     final ContentValues values = new ContentValues();
     values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
     values.put(MediaStore.MediaColumns.SIZE, size);
     final Uri uri = contentResolver.insert(filesUri, values);
     return contentResolver.openInputStream(uri);
   } catch (final Throwable t) {
     return null;
   }
 }
 /**
  * Deletes the file. Returns true if the file has been successfully deleted or otherwise does not
  * exist. This operation is not recursive.
  */
 public static boolean delete(final Context context, final File file) {
   final String where = MediaStore.MediaColumns.DATA + "=?";
   final String[] selectionArgs = new String[] {file.getAbsolutePath()};
   final ContentResolver contentResolver = context.getContentResolver();
   final Uri filesUri = MediaStore.Files.getContentUri("external");
   // Delete the entry from the media database. This will actually delete media files.
   contentResolver.delete(filesUri, where, selectionArgs);
   // If the file is not a media file, create a new entry.
   if (file.exists()) {
     final ContentValues values = new ContentValues();
     values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
     contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
     // Delete the created entry, such that content provider will delete the file.
     contentResolver.delete(filesUri, where, selectionArgs);
   }
   return !file.exists();
 }
  public static boolean rmdir(final File file, Context context) {
    if (file == null) return false;
    if (!file.exists()) {
      return true;
    }
    if (!file.isDirectory()) {
      return false;
    }
    String[] fileList = file.list();
    if (fileList != null && fileList.length > 0) {
      //  empty the folder.
      rmdir1(file, context);
    }
    String[] fileList1 = file.list();
    if (fileList1 != null && fileList1.length > 0) {
      // Delete only empty folder.
      return false;
    }
    // Try the normal way
    if (file.delete()) {
      return true;
    }

    // Try with Storage Access Framework.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      DocumentFile document = getDocumentFile(file, true, context);
      return document.delete();
    }

    // Try the Kitkat workaround.
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
      ContentResolver resolver = context.getContentResolver();
      ContentValues values = new ContentValues();
      values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
      resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

      // Delete the created entry, such that content provider will delete the file.
      resolver.delete(
          MediaStore.Files.getContentUri("external"),
          MediaStore.MediaColumns.DATA + "=?",
          new String[] {file.getAbsolutePath()});
    }

    return !file.exists();
  }
Example #10
0
  /**
   * 开始搜索
   *
   * @param filename
   */
  private void onStartSearchFile(String filename) {
    String volumeName = "external";
    Uri uri = MediaStore.Files.getContentUri(volumeName);
    String selection = MediaStore.Files.FileColumns.TITLE + " LIKE '%" + filename + "%'";
    String[] columns =
        new String[] {
          MediaStore.Files.FileColumns._ID,
          MediaStore.Files.FileColumns.DATA,
          MediaStore.Files.FileColumns.SIZE,
          MediaStore.Files.FileColumns.DATE_MODIFIED
        };
    Cursor cursor =
        getContext()
            .getContentResolver()
            .query(uri, columns, selection, null, MediaStore.Files.FileColumns.TITLE + " asc");

    List<FileInfo> list = (List<FileInfo>) getAllFiles(cursor);
    listView.setAdapter(new MyAdapter(list));
  }
Example #11
0
 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
 public static boolean deleteFile(String path) {
   boolean deleted = false;
   path = Uri.decode(Strings.removeFileProtocole(path));
   // Delete from Android Medialib, for consistency with device MTP storing and other apps listing
   // content:// media
   if (AndroidUtil.isHoneycombOrLater()) {
     ContentResolver cr = VLCApplication.getAppContext().getContentResolver();
     String[] selectionArgs = {path};
     deleted =
         cr.delete(
                 MediaStore.Files.getContentUri("external"),
                 MediaStore.Files.FileColumns.DATA + "=?",
                 selectionArgs)
             > 0;
   }
   File file = new File(path);
   if (file.exists()) deleted |= file.delete();
   return deleted;
 }
 public MediaFile(Context context, File file) {
   this.file = file;
   this.context = context;
   contentResolver = context.getContentResolver();
   filesUri = MediaStore.Files.getContentUri("external");
 }
 /** Returns an OutputStream to write to the file. The file will be truncated immediately. */
 private static int getTemporaryAlbumId(final Context context) {
   final File temporaryTrack;
   try {
     temporaryTrack = installTemporaryTrack(context);
   } catch (final IOException ex) {
     Log.w("MediaFile", "Error installing tempory track.", ex);
     return 0;
   }
   final Uri filesUri = MediaStore.Files.getContentUri("external");
   final String[] selectionArgs = {temporaryTrack.getAbsolutePath()};
   final ContentResolver contentResolver = context.getContentResolver();
   Cursor cursor =
       contentResolver.query(
           filesUri, ALBUM_PROJECTION, MediaStore.MediaColumns.DATA + "=?", selectionArgs, null);
   if (cursor == null || !cursor.moveToFirst()) {
     if (cursor != null) {
       cursor.close();
       cursor = null;
     }
     final ContentValues values = new ContentValues();
     values.put(MediaStore.MediaColumns.DATA, temporaryTrack.getAbsolutePath());
     values.put(MediaStore.MediaColumns.TITLE, "{MediaWrite Workaround}");
     values.put(MediaStore.MediaColumns.SIZE, temporaryTrack.length());
     values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg");
     values.put(MediaStore.Audio.AudioColumns.IS_MUSIC, true);
     contentResolver.insert(filesUri, values);
   }
   cursor =
       contentResolver.query(
           filesUri, ALBUM_PROJECTION, MediaStore.MediaColumns.DATA + "=?", selectionArgs, null);
   if (cursor == null) {
     return 0;
   }
   if (!cursor.moveToFirst()) {
     cursor.close();
     return 0;
   }
   final int id = cursor.getInt(0);
   final int albumId = cursor.getInt(1);
   final int mediaType = cursor.getInt(2);
   cursor.close();
   final ContentValues values = new ContentValues();
   boolean updateRequired = false;
   if (albumId == 0) {
     values.put(MediaStore.Audio.AlbumColumns.ALBUM_ID, 13371337);
     updateRequired = true;
   }
   if (mediaType != 2) {
     values.put("media_type", 2);
     updateRequired = true;
   }
   if (updateRequired) {
     contentResolver.update(filesUri, values, BaseColumns._ID + "=" + id, null);
   }
   cursor =
       contentResolver.query(
           filesUri, ALBUM_PROJECTION, MediaStore.MediaColumns.DATA + "=?", selectionArgs, null);
   if (cursor == null) {
     return 0;
   }
   try {
     if (!cursor.moveToFirst()) {
       return 0;
     }
     return cursor.getInt(1);
   } finally {
     cursor.close();
   }
 }