Android 第三方的使用(fastjson、okhttp3、butterknife、glide)

implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
//noinspection AnnotationProcessorOnCompilePath
implementation 'com.jakewharton:butterknife:10.2.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'
implementation 'com.alibaba:fastjson:1.2.72'
implementation 'com.squareup.okhttp3:okhttp:3.6.0'

 

    Glide.with(context)
                    .load(path)
                    .error(R.drawable.image_e)
                    .into(imageView);

Android Glide简单使用 https://blog.csdn.net/chennai1101/article/details/103985572

 

json

//对象转字符串
 String str = JSONObject.toJSONString(obj);

//字符串转对象
   JSONObject jsonObject = JSONObject.parseObject(s);
   String v= jsonObject.getString("key");
//转数组
JSONArray array = jsonObject .getJSONArray("array");

 

ButterKnife使用   

    @BindView(R.id.ListView )
    ListView listView;


onCreate中
  ButterKnife.bind(this);

    @OnClick({R.id.1,R.id.2,R.id.3, R.id.4,R.id.5})
    public void click(View v) {
}

   @OnItemClick(R.id.list)
    void onItemClick(int position) {
      
    }

 

 

okhttp

get


        OkHttpClient client = new OkHttpClient();
        final Request request;
        if(token==null){
            request = new Request.Builder().get().url(url).build();
        }else{
            request = new Request.Builder().get().url(url).addHeader("Authorization",  token).build();
        }
        L.e(request.toString());

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call,@NonNull IOException e) {
                if(callback!=null){
                    callback.onFail(action,e.toString());
                }
            }

            @Override
            public void onResponse(@NonNull Call call,@NonNull Response response)  {

                if(callback!=null){
                    callback.onSuccess(action,response);
                }
            }
        });
post   

     OkHttpClient client = new OkHttpClient();
   
   
        RequestBody body = FormBody.create(MediaType.parse("application/json"), postJson);
        final Request request;
        if (token == null) {
            request = new Request.Builder().post(body).url(url).build();
        } else {
            request = new Request.Builder().post(body).url(url).addHeader("Authorization", token).build();

        }
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call,@NonNull IOException e) {
                if (callback != null) {
                    callback.onFail(action, e.toString());
                }

            }

            @Override
            public void onResponse(@NonNull Call call,@NonNull Response response)   {
                if (callback != null) {
                    callback.onSuccess(action, response);
                }
            }
        });

 

 

 

 


//下载示例
public class DownApkThread extends Thread {
    private DownLoadCallback downLoadCallback;
    private String path;
    private String url;
    private MainApplication application;
    private ServerMgsBean mgsBean;
    private String checkCode;


    public DownApkThread(DownLoadCallback downLoadCallback, ServerMgsBean mgsBean, String path, String url, MainApplication application,String checkCode) {
        this.path = path;
        this.url = url;
        this.application = application;
        this.downLoadCallback = downLoadCallback;
        this.mgsBean = mgsBean;
        this.checkCode = checkCode;

    

    }

    @Override
    public void run() {
        super.run();
        cleanFile(path);
        L.e("开始下载文件,下载地址:"+Datas.downLoadIp+url);
        writeLog("开始下载文件,下载地址:"+Datas.downLoadIp+url,application);

        OkHttpClient client = new OkHttpClient();
        //请求超时设置
        client.newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(4 * 60, TimeUnit.SECONDS)
                .build();

        final Request request;
        request = new Request.Builder()
                .url(Datas.downLoadIp+url)
                .get()
                .build();

        Call call = client.newCall(request);

            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    L.e("下载失败:" + e.toString());
                    writeLog("下载失败:"+e.toString(),application);
                    if(downLoadCallback!=null){
                        downLoadCallback.onFail(mgsBean,e.toString());
                    }


                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    String[] s = url.split("/");
                    String fileName = s[s.length - 1];
                    InputStream is = null;//输入流
                    FileOutputStream fos = null;//输出流
                    File   file = new File(path, fileName);// 设置路径
                    if (response.code() == 200) {
                    try {
                        is = response.body().byteStream();//获取输入流
                        if (is != null) {
                            L.e("存储父路径:" + path);

                            File fileParent = new File(path);

                            if (!fileParent.exists()) {
                                fileParent.mkdirs();
                                L.e("存储父路径创建完成");
                            } else {
                                L.e("存储父路径已存在");
                            }


                            L.e("文件地址:" + file.toString());
                            if (file.exists()) {
                                file.delete();
                                L.e("文件地址以存在,删除");
                            } else {
                                L.e("文件不存在");
                            }
                            L.e("准备创建文件");
                            file.createNewFile();
                            L.e("重新创建文件");

                            fos = new FileOutputStream(file);
                            byte[] buf = new byte[1024];
                            int ch = -1;
                            while ((ch = is.read(buf)) != -1) {
                                fos.write(buf, 0, ch);

                            }
                        }
                        fos.flush();
                        // 下载完成
                        if (fos != null) {
                            fos.close();
                        }
                        writeLog("下载完成:" + path, application);
                        //下载完成
                        L.e(checkCode);
                        L.e(FileUtils.getFileHex(file.getPath()));
                        if(FileUtils.checkHex(file.getPath(),checkCode)){
                            //校验正确

                            if (downLoadCallback != null) {
                                downLoadCallback.onSuccess(mgsBean, path + "/" + fileName);
                            }
                        }else{
                            //校验错误

                            if (downLoadCallback != null) {
                                downLoadCallback.onFail(mgsBean, "校验错误");
                            }
                        }

                    } catch (Exception e) {
                        //下载失败
                        writeLog("下载失败:" + e.toString(), application);

                        if (downLoadCallback != null) {
                            downLoadCallback.onFail(mgsBean, e.toString());
                        }
                        L.e(e.toString());
                    } finally {
                        try {
                            if (is != null)
                                is.close();
                        } catch (IOException e) {
                        }
                        try {
                            if (fos != null)
                                fos.close();
                        } catch (IOException e) {
                        }
                    }

                }else{
                        L.e("下载失败:code=" + response.code());
                        writeLog("下载失败:code=" + response.code(), application);
                        if (downLoadCallback != null) {
                            downLoadCallback.onFail(mgsBean, "下载失败:code=" + response.code());
                        }

                    }
                }
            });




    }


    private void writeLog(String log, Context context){
        WriteFileUtil.writefile(context.getExternalFilesDir(null)+"/log/","DownLoad.txt","\r\n"+getDateTimeStr()+log);

    }
    private static String getDateTimeStr(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd_HH:mm:ss___");
        Date date = new Date();
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }
    /**
     * @method
     * @description 清理空间,当文件夹类文件大于一定数量时,清空
     * @date: 2020/3/31 10:57
     * @param
     * @return
     */
    private void cleanFile(String path){

        File fileParent = new File(path);

        if (fileParent.exists()) {
            double size  = FileUtils.getFileOrFilesSize(path,FileUtils.SIZETYPE_MB);
            L.e("当前文件夹大小:"+size+"MB");
            if(size>Datas.maxDownFileSize){
                deleteFile(path);
            }
        }

    }

    private void deleteFile(String path){

        File file = new File(path);

        if(!file.exists()) return;

        if(file.isFile() || file.list()==null) {
            file.delete();
            L.e("删除了"+file.getName());
        }else {
            File[] files = file.listFiles();
            for(File a:files) {
                deleteFile(a.getPath());
            }
            file.delete();
            L.e("删除了"+file.getName());
        }



    }



}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值