【问题标题】:Cancel downloading a File with OkHttp3使用 OkHttp3 取消下载文件
【发布时间】:2020-01-13 13:18:45
【问题描述】:

我想用 Okio 取消下载的文件,它在 AsyncTaks 中运行当我取消 Asynctask downloadedFilerunTask.cancel() 我可以使用 break 摆脱下载过程,但下载的过程没有取消,如何我可以取消下载的流并在 android 中停止 AsynTask

@Override
protected String doInBackground(String... strings) {

    for(int i=0; i<fileList.size(); i++) {    
        if (Utils.getStatusAbort()) {

                                      request = new Request.Builder().url(fileList.get(i))
                        .addHeader("Authorization", header)
                        .addHeader("Content-Type", "application/json")
                        .build();
                try {
                    okhttp3.Response response = client.newCall(request).execute();
                    ResponseBody body = response.body();
                    int finalI = i;
                    ZipFile zipFile;

                    if (response.isSuccessful()) {
                        try {
                            Log.i("body", "" + body);
                            destFilePath = Utils.getDestFilePath(context, fileNameList.get(i));
                            downloadedFile = new File(destFilePath, fileNameList.get(i));
                            BufferedSink sink = Okio.buffer(Okio.sink(downloadedFile));
                            if (response.body() != null) {
                                sink.writeAll(response.body().source());
                            }
                            sink.close();

                            Utils.savedStateOfApp(context, "publish");

                            //Log.i("md5:" + md5List.get(i), " = " + Utils.calculateMD5(new File(Utils.getDestFilePath(context, fileNameList.get(i)) + "/" + fileNameList.get(i))));

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);

}

【问题讨论】:

    标签: android android-asynctask okio


    【解决方案1】:

    您需要在使用client.newCall(request) 创建的Call 对象上调用cancel()。在AsyncTask中实现onCancelled()方法:

    @Override
    protected void onCancelled() {
        if (call != null) {
            call.cancel();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2022-06-25
      相关资源
      最近更新 更多