Android工具集

OkHttp通过绑定服务下载文件

2017-08-31  本文已影响73人  Small_Cake
  1. 首先我们需要在AndroidManifest.xml中加入权限和服务(读写权限6.0+需要动态申请,这里不做介绍)
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/cake"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/cake"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <service android:name="com.smallcake.okhttp.SmallDownloadService"/>

    </application>

2.调用下载方法

private void down() {
        String downUrl = "https://downpack.baidu.com/appsearch_AndroidPhone_v7.9.3(1.0.64.143)_1012271b.apk";
        String savePath = Environment.getExternalStorageDirectory()+ File.separator + Environment.DIRECTORY_DOWNLOADS+ File.separator;
        String saveName = "百度助手.apk";
        SmallOkHttp.downloadUIWithService(this, downUrl, savePath, saveName, new DownloadListener() {
            @Override
            public void start(long totalSize) {
                L.i(" 开始下载 " + totalSize);
            }
            @Override
            public void downloading(int percentage, long currentSize) {
                L.i("下载进度==" + percentage + "% 已下载== " + FormatUtils.formatSize(MainActivity.this, currentSize));
                progressBar.setProgress(percentage);
            }
            @Override
            public void successed(String successPath, String successFileName) {
                L.i(successFileName + " 已保存至 " + successPath);
            }
            @Override
            public void failed(IOException e) {
                L.i(" 下载失败 " + e.getMessage());

            }
        });
    }

这样我们就把需要的文件下载下来了,如果不想写路径和文件名称,它会默认下载到手机Download路径下,保存的文件名称会是下载连接的文件名称,不管下载成功还是失败,最后都会关闭服务!好,到这里,OkHttp的简单下载文件到手机就介绍完了!

上一篇下一篇

猜你喜欢

热点阅读