Java tutorial
/* * Copyright (c) 2015 eneim. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package im.ene.lab.dowy.internal; import android.os.Environment; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import im.ene.lab.dowy.OnProgressListener; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.Callable; /** * Created by eneim on 11/27/15. */ class PartDownloader implements Callable<File> { private final OkHttpClient client; private final Request request; private final OnProgressListener listener; public PartDownloader(OkHttpClient client, Request request, OnProgressListener listener) { this.client = client; this.request = request; this.listener = listener; this.client.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), PartDownloader.this.listener)) .build(); } }); } @Override public File call() throws Exception { Response response = client.newCall(request).execute(); File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "/part_" + request.hashCode()); if (file.exists()) { file.delete(); } if (file.createNewFile()) { InputStream stream = response.body().byteStream(); FileUtil.saveStreamToFile(file, stream); } return file; } }