Andorid 保存MP4视频到相册

938 阅读1分钟

保存MP4视频到相册

1.通过发送广播扫描本地文件到相册(不能全部兼容)

ContentResolver localContentResolver = context.getContentResolver();
ContentValues localContentValues = getVideoContentValues(new File(path), System.currentTimeMillis());
Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));

测试:一加7pro无效 与 荣耀V10在相册可以看到

2.通过scanFile方式加入到相册(没用)

MediaScannerConnection mediaScanner;
mediaScanner = new MediaScannerConnection(context, new MediaScannerConnection.MediaScannerConnectionClient() {
    @Override
    public void onMediaScannerConnected() {
        if (mediaScanner != null && mediaScanner.isConnected()) {
            mediaScanner.scanFile(path, "video/mp4");
        }
    }

    @Override
    public void onScanCompleted(String path, Uri uri) {

    }
});
mediaScanner.connect();

测试:一加7pro无效 与 荣耀V10无效

以上方式我都试过不能在一加上通行,后来看到抖音保存编辑的视频是复制了一份文件到相册目录下。

3.复制文件或移动文件到相册目录下,再发送通知扫描文件到相册(正在使用)

 try {
 //复制文件到相册目录下
    File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsoluteFile();
    String resultPath = file.getPath() + "/Camera/" + System.currentTimeMillis() + "snake_video.mp4";
    outChannel = new RandomAccessFile(resultPath, "rwd").getChannel();
    FileInputStream in = new FileInputStream(path);
    inChannel = in.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    inChannel.close();
    outChannel.close();
               ```
    //映射到相册
    ContentResolver localContentResolver = context.getContentResolver();
    ContentValues localContentValues = getVideoContentValues(new File(path1), System.currentTimeMillis());
    Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));
 } catch (Exception e) {
     e.printStackTrace();
     try {
         if (outChannel != null) {
             outChannel.close();
         }
     } catch (Exception e1) {
         e1.printStackTrace();
     }
     try {
         if (inChannel != null) {
             inChannel.close();
         }
     } catch (Exception e1) {
         e1.printStackTrace();
     }
 }
});

目前来看一加7pro 与 荣耀V10 都没有问题。

先就这样了,做个记录,给测试去测了,等下云测一下,试试看别的机型兼容情况,随时更新。欢迎大家一起来探讨,网上资料有点难找,或者提供好用开源框架学习一下,有什么机型不适配,都可以告诉我,会尽快解决。