FileUtil.java 7.57 KB
package com.glsx.commonres.util;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.glsx.commonres.CommonResApp;
import com.glsx.commonres.file.FileMediaType;

import java.io.File;
import java.io.FileNotFoundException;
/**
 * Author by zh, Date on 2022/3/2.
 * PS: write a bug or more,please indicate.
 * 文件操作工具类
 */
@SuppressWarnings("deprecation")
public class FileUtil {
    private static final String TAG = FileUtil.class.getSimpleName();

    @SuppressWarnings("deprecation")
    public static void saveFileToGallery(String filepath) {
        if(TextUtils.isEmpty(filepath)){
            return;
        }
        Context context = CommonResApp.getContext();
        File file = new File(filepath);
        if(!file.exists()){
            return;
        }
        String filename = file.getName();
        int fileType = FileMediaType.getMediaType(filename);

        // 其次把文件插入到系统图库
        if (FileMediaType.IMAGE_TYPE == fileType) {
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        file.getAbsolutePath(), filename, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 判断SDK版本是不是4.4或者高于4.4
                String[] paths = new String[]{file.getAbsolutePath()};
                MediaScannerConnection.scanFile(context, paths, null, null);
            } else {
                final Intent intent;
                if (file.isDirectory()) {
                    intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
                    intent.setClassName("com.android.providers.media",
                            "com.android.providers.media.MediaScannerReceiver");
                    intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
                } else {
                    intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    intent.setData(Uri.fromFile(file));
                }
                context.sendBroadcast(intent);
            }
        } else if (FileMediaType.VIDEO_TYPE == fileType) {
            final Intent intent;
            intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file));
            context.sendBroadcast(intent);
        }

    }

    @SuppressWarnings("deprecation")
    public static void saveFileToGallery(Context context, String filepath) {
        LogUtils.dTag(TAG, "saveFileToGallery:filepath = " + filepath);
        if (TextUtils.isEmpty(filepath)) {
            return;
        }

        /*循环视频的task中文件路径是.ts结尾,下载完成后.ts文件重新命名为.mp4,.ts文件被删除,
         *所以filepath的结尾是.ts,导致文件不存在.故在更新媒体库之前要将文件格式进行修改*/
        if (filepath.endsWith(".ts"))
            filepath = filepath.substring(0, filepath.lastIndexOf(".ts")) + ".mp4";
        else if (filepath.endsWith(".tstmp"))
            filepath = filepath.substring(0, filepath.lastIndexOf(".tstmp")) + ".mp4";

        LogUtils.i(TAG, "trans filepath = " + filepath);

        File file = new File(filepath);
        if (!file.exists()) {
            LogUtils.dTag(TAG, "saveFileToGallery:file.exists() = false");
            return;
        }
        String filename = file.getName();
        int fileType = FileMediaType.getMediaType(filename);
        LogUtils.dTag(TAG, "saveFileToGallery:fileType = " + fileType);

        // 其次把文件插入到系统图库
        if (FileMediaType.IMAGE_TYPE == fileType) {
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        file.getAbsolutePath(), filename, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 判断SDK版本是不是4.4或者高于4.4
                String[] paths = new String[]{file.getAbsolutePath()};
                MediaScannerConnection.scanFile(context, paths, null, null);
            } else {
                final Intent intent;
                if (file.isDirectory()) {
                    intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
                    intent.setClassName("com.android.providers.media",
                            "com.android.providers.media.MediaScannerReceiver");
                    intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
                } else {
                    intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    intent.setData(Uri.fromFile(file));
                }
                context.sendBroadcast(intent);
            }
        } else if (FileMediaType.VIDEO_TYPE == fileType) {
//            final Intent intent;
//            intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file));
//            context.sendBroadcast(intent);
//
//            ContentValues values = new ContentValues();
//            values.put(MediaStore.Video.Media.DATA, filepath);
//            File filesave = new File(filepath);
//
//            context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, getVideoContentValues( filesave,System.currentTimeMillis()));
            saveVideo(context, filepath);
        }
    }

    private static void saveVideo(Context context, String filepath) {
        LogUtils.dTag(TAG, "saveVideo:filepath = " + filepath);
        if (TextUtils.isEmpty(filepath)) {
            return;
        }


        if (null != context) {
            ContentResolver localContentResolver = context.getContentResolver();
            if (null != localContentResolver) {
                File file = new File(filepath);
                ContentValues localContentValues = getVideoContentValues(file, System.currentTimeMillis());
                Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
                if (null != localUri) {
                    LogUtils.dTag(TAG, "saveVideo:localUri = " + localUri.toString());
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));
                }
            }
        }
    }

    @SuppressWarnings("deprecation")
    private static ContentValues getVideoContentValues(File paramFile, long paramLong) {

        ContentValues localContentValues = new ContentValues();
        localContentValues.put(MediaStore.Video.Media.TITLE, paramFile.getName());
        localContentValues.put(MediaStore.Video.Media.DISPLAY_NAME, paramFile.getName());
        localContentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
        localContentValues.put(MediaStore.Video.Media.DATE_TAKEN, paramLong);
        localContentValues.put(MediaStore.Video.Media.DATE_MODIFIED, paramLong);
        localContentValues.put(MediaStore.Video.Media.DATE_ADDED, paramLong);
        localContentValues.put(MediaStore.Video.Media.DATA, paramFile.getAbsolutePath());
        localContentValues.put(MediaStore.Video.Media.SIZE, paramFile.length());
        return localContentValues;
    }
}