首页 > 代码库 > 从MediaStorehe和sd中删除媒体文件

从MediaStorehe和sd中删除媒体文件

参考资料:http://www.sandersdenardi.com/querying-and-removing-media-from-android-mediastore/

从媒体表中删除:

private void delSourceFile(final String filePath) {
        ThreadFactory.getNormaPool().execute(new Runnable() {
            @Override
            public void run() {
                String[] retCol = {MediaStore.Audio.Media._ID};
                Cursor cur = mActivity.getContentResolver().query(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                        retCol,
                        MediaStore.MediaColumns.DATA + "=‘" + filePath + "‘", null, null);
                if (cur.getCount() == 0) {
                    return;
                }
                cur.moveToFirst();
                int id = cur.getInt(cur.getColumnIndex(MediaStore.MediaColumns._ID));
                LogUtil.getLog().e("id=" + filePath);
                cur.close();

                try {
                    Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                            id);
                    mActivity.getContentResolver().delete(uri, null, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

从本地删除:

/**
* 从SD卡中删除文件
*/
public static void deleteFile(File file) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
}
// 如果它是一个目录
else if (file.isDirectory()) {
// 声明目录下所有的文件 files[];
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
}
}
file.delete();
}
}
}

从MediaStorehe和sd中删除媒体文件