在 Android Studio 中重命名来自 MediaStore 的视频需要借助 MediaStore API
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
private void renameVideoInMediaStore(String oldPath, String newPath) {
ContentResolver contentResolver = getContentResolver();
// 从 MediaStore 中获取视频
Uri videoUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Video.Media.DATA + "=?";
String[] selectionArgs = new String[]{oldPath};
Cursor cursor = contentResolver.query(videoUri, null, selection, selectionArgs, null);
try {
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Video.Media.DATA, newPath);
// 更新 MediaStore 中的视频
int updateResult = contentResolver.update(videoUri, contentValues, MediaStore.Video.Media._ID + "=?", new String[]{String.valueOf(id)});
if (updateResult > 0) {
Toast.makeText(this, "视频重命名成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "视频重命名失败", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "视频重命名失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
renameVideoInMediaStore
方法重命名视频:String oldVideoPath = "/storage/emulated/0/DCIM/Camera/sample_video.mp4";
String newVideoPath = "/storage/emulated/0/DCIM/Camera/new_sample_video.mp4";
renameVideoInMediaStore(oldVideoPath, newVideoPath);
领取专属 10元无门槛券
手把手带您无忧上云