Android 封装okgo通用下载文件到手机指定目录下的工具类

1、封装通用的下载文件工具类

package com.ywb.tuyue.download;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.base.Request;
import java.io.File;
/**
 * Description: 使用okgo下载文件 zip video music txt image
 * Created by wcystart on 2018/7/4.
 */
public class DownLoadFileUtils {
    private static String mBasePath; //本地文件存储的完整路径  /storage/emulated/0/book/恰似寒光遇骄阳.txt
    /**
     *
     * @param context 上下文
     * @param fileUrl 下载完整url
     * @param destFileDir  SD路径
     * @param destFileName  文件名
     * @param mFileRelativeUrl 下载相对地址
     * (我们从服务器端获取到的数据都是相对的地址)例如: "filepath": "/movie/20180511/1526028508.txt"
     */
    public static void downloadFile(Context context, String fileUrl, String destFileDir,String destFileName,String mFileRelativeUrl){
        String  mDestFileName =destFileName+mFileRelativeUrl.substring(mFileRelativeUrl.lastIndexOf("."),mFileRelativeUrl.length());
        OkGo.get(fileUrl).tag(context).execute(new FileCallback(destFileDir,mDestFileName) { //文件下载时指定下载的路径以及下载的文件的名称
            @Override
            public void onStart(Request request) {
                super.onStart(request);
                LogUtils.e("开始下载文件"+"DDDDD");
            }

            @Override
            public void onSuccess(com.lzy.okgo.model.Response response) {
                LogUtils.e("下载文件成功"+"DDDDD"+response.body().length());
                mBasePath=response.body().getAbsolutePath();
             }

            @Override
            public void onFinish() {
                super.onFinish();
                LogUtils.e("下载文件完成"+"DDDDD");
                SPUtils.getInstance().put("localPath",mBasePath);
            }

            @Override
            public void onError(com.lzy.okgo.model.Response response) {
                super.onError(response);
                LogUtils.e("下载文件出错"+"DDDDD"+response.message());

            }

            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                float  dLProgress= progress.fraction;
                LogUtils.e("文件下载的进度"+"DDDDD"+dLProgress);
            }
        });
    }

    //拼接一个本地的完整的url 供下载文件时传入一个本地的路径
    private static final String mSDPath = Environment.getExternalStorageDirectory().getPath();
    //分类别路径
    private static String mClassifyPath=null;
    public static String customLocalStoragePath(String differentName){
        File basePath=new File(mSDPath); // /storage/emulated/0
        mClassifyPath=mSDPath+"/"+differentName+"/";  //如果传来的是 book 拼接就是 /storage/emulated/0/book/
                                                    //如果传来的是game  那拼接就是 /storage/emulated/0/game/
        if(!basePath.exists()){
            basePath.mkdirs();
            System.out.println("文件夹创建成功");
        }

        return mClassifyPath;
    }


    //截取一个文件加载显示时传入的一个本地完整路径
    public static String subFileFullName(String fileName,String fileUrl){
        String cutName=fileName+fileUrl.substring(fileUrl.lastIndexOf("."),fileUrl.length());  //这里获取的是  恰似寒光遇骄阳.txt
        return cutName;
    }
}

2、举例在需要下载的时候使用这个工具类 //比如下载图片

package com.ywb.tuyue.ui.unlock;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.ywb.tuyue.MyApplication;
import com.ywb.tuyue.R;
import com.ywb.tuyue.constants.Constants;
import com.ywb.tuyue.constants.IpConfig;
import com.ywb.tuyue.db.dao.CountDao;
import com.ywb.tuyue.download.DownLoadFileUtils;
import com.ywb.tuyue.entity.Count;
import com.ywb.tuyue.entity.StickyEvent;
import com.ywb.tuyue.entity.TAdvertList;
import com.ywb.tuyue.entity.TAdvertType;
import com.ywb.tuyue.ui.main.MainActivity;
import com.ywb.tuyue.ui.mvp.BaseActivity;
import com.ywb.tuyue.ui.splash.SplashActivity;
import com.ywb.tuyue.utils.GlideUtils;
import com.ywb.tuyue.utils.PreferencesUtils;
import com.ywb.tuyue.widget.CustomerUnlockView;
import org.greenrobot.eventbus.EventBus;
import java.util.List;
import javax.inject.Inject;
public class UnlockActivity extends BaseActivity {
    //TODO: 2018/6/20 控件
    private ImageView mUnlockAdvertImage;
    private CustomerUnlockView mCustomerUnlockView;
    String mUnlockImageUrl;
    @Override
    public int bindLayout() {
        return R.layout.activity_unlock;
    }
    @Override
    public void initParms(Bundle parms) {
        //parms.getString()
        // TODO: 2018/6/20 接收参数
    }
 @Override
    public void initView(View view) {
        //接收从flash页中传过来的参数 获取的是图片的相对路径:/advert/20180706/1530849977.jpg
        mUnlockImageUrl = (String) mOperation.getParameter(Constants.UNLOCK_IMAGE_URL);

        // TODO: 2018/6/20 布局
        mUnlockAdvertImage = findViewById(R.id.unlock_bg_advert); //图片容器
        mCustomerUnlockView = findViewById(R.id.unlock_view);

        **//下载图片
        String imageUrl = IpConfig.BASE_IMAGE_URL + mUnlockImageUrl;//http://47.98.121.127/upload/advert/20180706/1530849977.jpg
        String localPath = DownLoadFileUtils.customLocalStoragePath("image");// /storage/emulated/0/image/
        DownLoadFileUtils.downloadFile(this, imageUrl, localPath, "suoping", mUnlockImageUrl);
        //localPath+DownLoadFileUtils.subFileFullName("suoping",mUnlockImageUrl)就是:/storage/emulated/0/image/suoping.jpg  本地SD卡中图片存储的完整路径
        //拿本地路径通过Glide加载到imageView控件中
        Glide.with(this).load(localPath+DownLoadFileUtils.subFileFullName("suoping",mUnlockImageUrl)).into(mUnlockAdvertImage);**
    }
    @Override
    public void doBusiness(Context mContext) {
        // TODO: 2018/6/20  业务调用
    }

    @Override
    public void initInjector() {
        getComponent().inject(this);
    }
}

3、这就是使用okgo将文件一边下载一边保存到本地指定SD卡目录下的一个使用流程!!!

你可能感兴趣的:(android网络)