IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> android 下载图片并刷新相册 -> 正文阅读

[移动开发]android 下载图片并刷新相册

public class HelpOpenFileUtils {

    /**
     * 读写权限
     */
    protected static final int WRITE_PERMISSION = 20003;
    protected static final String[] WRITEPERMISSION = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private static final String TAG = "TAG_HelpOpenFileUtils";

    public static void nativeDownloadFile(final Activity context, String url, final File downloadFile) {
        OkHttpClient httpClient = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(url).get().build();
        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("TAG_文件下载", "onFailure");
                ToastUtil.showToast("下载文件失败!!!");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                if (code >= 500) {
                    Log.e("TAG_文件下载", "code=" + code);
                    ToastUtil.showToast("下载文件失败!!!");
                } else if (code >= 200 && code < 300) {
                    InputStream is = response.body().byteStream();
                    byte[] buf = new byte[8 * 1024];
                    int len = 0;
                    long sum = 0;
                    OutputStream fos = null;
                    try {
                        Log.e("TAG_文件下载", "downloadFile=" + downloadFile);
                        fos = new FileOutputStream(downloadFile);

                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                        }
                        fos.flush();
                        // 通知图库更新
                        LocalBroadcastManager.getInstance(MyApplication.getInstance()).sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(downloadFile.getAbsolutePath())));

                        ToastUtil.showToast("图片保存成功!");

                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e("TAG_文件下载", "IOException=");
                       ToastUtil.showToast("下载文件失败!!!");
                    } finally {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    }
                }

            }
        });
    }

    //文件下载
    public static File createFile(FragmentActivity context, String url) {
        if (url.indexOf(".") != -1) {
            String type = url.substring(url.lastIndexOf(".") + 1);
            Log.e(TAG, "createFile===type=" + type);
            PermissionsChecker mChecker = new PermissionsChecker(context);
            if (mChecker.lacksPermissions(WRITEPERMISSION)) {
                // 请求权限
                PermissionsActivity.startActivityForResult((Activity) context, WRITE_PERMISSION, WRITEPERMISSION);
            } else {
                // 全部权限都已获取
                Log.e(TAG, "createFile===url=" + url);
                if (TextUtils.isEmpty(url)) {
                    Log.e(TAG, "downloadFile: url下载地址为空!!!");
                    return null;
                }
                try {
                    int indexOf = url.indexOf("file_name=");
                    if (indexOf != -1) {
                        url = url.substring(0, indexOf + 10) + URLEncoder.encode(url.substring(indexOf + 10), "UTF-8");
                        Log.e(TAG, "createFile===url=" + url);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                File downloadFile = createDefaultTimeFile(type);
                if (null == downloadFile) {
                    Log.e(TAG, "downloadFile: 文件创建失败!!!");
                    return null;
                }
                return downloadFile;
            }
        }
        return null;
    }

    //文件下载
    public static void downloadFile(Activity context, String url) {
        if (url.indexOf(".") != -1) {
            int dian = url.lastIndexOf(".") + 1;
            String type = "";
            if (url.indexOf("/?") != -1) {
                int i = url.lastIndexOf("/?");
                type = url.substring(dian, i);
            } else if (url.indexOf("?") != -1) {
                int i = url.lastIndexOf("?");
                type = url.substring(dian, i);
            } else {
                type = url.substring(dian);
            }

            downloadFile(context, url, type);
        }
    }

    public static void downloadFile(Activity context, String url, String type) {
        Log.e(TAG, "type=" + type);
        PermissionsChecker mChecker = new PermissionsChecker(context);
        if (mChecker.lacksPermissions(WRITEPERMISSION)) {
            // 请求权限
            PermissionsActivity.startActivityForResult((Activity) context, WRITE_PERMISSION, WRITEPERMISSION);
        } else {
            // 全部权限都已获取
            Log.e(TAG, "url=" + url);
            if (TextUtils.isEmpty(url)) {
                Log.e(TAG, "downloadFile: url下载地址为空!!!");
                return;
            }
            try {
                int indexOf = url.indexOf("file_name=");
                if (indexOf != -1) {
                    url = url.substring(0, indexOf + 10) + URLEncoder.encode(url.substring(indexOf + 10), "UTF-8");
                    Log.e(TAG, "url=" + url);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            File downloadFile = createDefaultTimeFile(type);
            if (null == downloadFile) {
                Log.e(TAG, "downloadFile: 文件创建失败!!!");
                return;
            }
            nativeDownloadFile(context, url, downloadFile);
        }
    }
    public static String dateFormat(long times, String dateformat) {
        if (times <= 0)
            return "";
        SimpleDateFormat dateformat1 = new SimpleDateFormat(dateformat);
        String dateStr = dateformat1.format(times);
        return dateStr;
    }
    private static File createDefaultTimeFile(String type) {
        String fileName = dateFormat(System.currentTimeMillis(), "yyyyMMddHHmmss");
       String mDownloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "download";
        File downloadFile = new File(mDownloadDir, fileName + "." + type);
        return createFile(downloadFile);
    }

    public static File createFile(File file) {
        Log.e(TAG, "file=" + file.toString());
        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                Log.e(TAG, "createFile: 目录创建失败!!!");
                return null;
            }
        }
        try {
            file = new File(file.toString());
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return file;

    }
 public static String dateFormat(long times, String dateformat) {
        if (times <= 0)
            return "";
        SimpleDateFormat dateformat1 = new SimpleDateFormat(dateformat);
        String dateStr = dateformat1.format(times);
        return dateStr;
    }

}

这是下载文件工具类,使用时直接HelpOpenFileUtils.downloadFile(this,url);即可

附带一个实用工具类ToastUtil

public class ToastUtil {
    private static Toast toast;

    private static Handler mHandler = new Handler(Looper.getMainLooper());

    public static void showToast(String text) {
        showToast(text, Toast.LENGTH_SHORT);
    }

    public static void showToast(int text) {
        showToast(BaseApp.getAppContext().getString(text), Toast.LENGTH_SHORT);
    }

    private static void showToast(final String text, final int duration) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            show(text, duration);
        } else {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    show(text, duration);
                }
            });
        }
    }

    private static void show(String text, int duration) {
        if (toast != null) {
            toast.cancel();
        }
        Log.e("TAG_Toast","text="+text);
        if (!TextUtils.isEmpty(text)){
            toast = Toast.makeText(BaseApp.getAppContext(),text, duration);
            toast.show();
        }
    }
}
 

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-07-24 11:36:36  更:2021-07-24 11:37:37 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/2 6:19:35-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码