Android之---下载带进度条(okhttp)

Android之—下载带进度条(okhttp)

Android之—下载带进度条(okhttp)

一、布局文件添加进度条
<ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_marginBottom="50dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>
二、添加下载监听接口DownloadProgressListener.java

注释:根据不同的情况,调用不同的方法

public interface DownloadProgressListener {
	// 下载中使用这个方法
    void onDownloadProgress(long sumReaded, long content, boolean done);
	// 下载结果,如下载中断等
    void onDownloadResult(long sumReaded, long content, boolean done);
	// 下载失败使用这个方法,如无法联网等
    void onFailResponse();
}
三、新建下载工具类DownloadUtil.java
public class DownloadUtil{
    
    /**
     * 带进度下载模式:DownloadProgressListener进度监听器
     *
     * @param url
     * @param listener
     */
    public static void download(final String url, final DownloadProgressListener listener){
        // 设置响应时间
        OkHttpClient client=new OkHttpClient.Builder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(3,TimeUnit.SECONDS)
                .build();
        Request request=new Request.Builder()
                .url(url)
                .build();
        Call call=client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onFailResponse();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                File file=FileUtil.generateFile(url);
				InputStream is=response.body().byteStream();   //相应体获得inputStream
                BufferedInputStream bis=new BufferedInputStream(is);//将inputstream转换成bufferedinputstream
                byte[] content = new byte[1024];
                int len=0;                                          //每次读取长度
                long sumReaded = 0L;
                long contentSize=response.body().contentLength();   //下载文件总长度
                FileOutputStream fos=new FileOutputStream(file);    //创建fileOutputStream
                while((len=bis.read(content))!=-1){                 //循环获取字节流
                    fos.write(content,0,len);                  //写入文件,读取byte[]中的缓存
                    sumReaded+=len;                                 //获取已下载长度
                    listener.onDownloadProgress
                            (sumReaded,contentSize,len==-1); //监听下载进度,是否下载完成
                }
                listener.onDownloadResult(sumReaded,contentSize,len==-1);
                fos.flush();
                fos.close();
                bis.close();
                is.close();
            }
        });
    }
}
四、利用下载工具类就可以下载文件了

注释:就是实现接口,实现接口方法(例如下载时执行onDownloadProgress方法,将下载进度显示在进度条上)

public void download(){
        DownloadUtil.download(url_cab, new DownloadProgressListener() {
				@Override
				public void onDownloadProgress(long sumReaded, long content, boolean done) {
					progressBar.setProgress((int)(sumReaded*100/content));
				}

				@Override
				public void onDownloadResult(long sumReaded, long content, boolean done) {
					if(done){
						runOnUiThread(new Runnable() {
								@Override
								public void run() {
									Toast.makeText(Activity_QD.this,"下载完成",Toast.LENGTH_SHORT).show();
								}
							});
						nextActivity();
					}
					
					else{
						runOnUiThread(new Runnable() {
								@Override
								public void run() {
									Toast.makeText(Activity_QD.this,"下载不完整",Toast.LENGTH_SHORT).show();
								}
							});
					}
				}

				@Override
				public void onFailResponse() {

					runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(Activity_QD.this,"无法联网",Toast.LENGTH_SHORT).show();
							}
						});
					try {
						Thread.sleep(1000);
						nextActivity();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});

    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Kotlin 中使用 OkHttp3 下载文件并下载进度,可以通过以下步骤实现: 1. 添加 OkHttp3 依赖 在 app module 的 build.gradle 文件中添加以下代码: ``` dependencies { implementation 'com.squareup.okhttp3:okhttp:4.9.0' } ``` 2. 创建 OkHttp3 客户端 在代码中创建一个 OkHttpClient 客户端: ``` val client = OkHttpClient() ``` 3. 创建下载请求 使用 OkHttp3 的 Request.Builder 创建一个下载请求,并设置下载 URL 和保存文件的路径: ``` val request = Request.Builder() .url("https://example.com/file.zip") .build() ``` 4. 创建下载监听器 定义一个回调接口,用于监听下载进度: ``` interface DownloadListener { fun onDownloadProgress(progress: Int) } ``` 在代码中实现这个接口,并在其中更新下载进度,例如: ``` val listener = object : DownloadListener { override fun onDownloadProgress(progress: Int) { runOnUiThread { // 更新下载进度条 progressBar.progress = progress } } } ``` 5. 发起下载请求 使用 OkHttpClient 的 newCall 方法发起下载请求,并在 enqueue 方法中传入一个 Callback 参数,该参数将在下载完成时回调: ``` client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { // 下载失败 } override fun onResponse(call: Call, response: Response) { val inputStream: InputStream = response.body?.byteStream() ?: return // 保存文件并更新下载进度 val totalSize: Long = response.body?.contentLength() ?: -1 var downloadedSize: Long = 0 val outputStream = FileOutputStream("/storage/emulated/0/Download/file.zip") val buffer = ByteArray(8192) while (true) { val bytes = inputStream.read(buffer) if (bytes == -1) break outputStream.write(buffer, 0, bytes) downloadedSize += bytes val progress = (downloadedSize * 100 / totalSize).toInt() listener.onDownloadProgress(progress) } outputStream.close() inputStream.close() // 下载完成 } }) ``` 这段代码中,我们首先从 response.body 中获取输入流并创建输出流,然后使用循环逐段读取输入流的数据,再将其写入输出流,并计算下载进度,最后调用 DownloadListener 的 onDownloadProgress 方法更新下载进度。在下载完成后,我们需要关闭输入流和输出流,以及在 onFailure 方法中处理下载失败的情况。 6. 完整代码 最终的代码应该类似于这样: ``` interface DownloadListener { fun onDownloadProgress(progress: Int) } val client = OkHttpClient() val request = Request.Builder() .url("https://example.com/file.zip") .build() val listener = object : DownloadListener { override fun onDownloadProgress(progress: Int) { runOnUiThread { // 更新下载进度条 progressBar.progress = progress } } } client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { // 下载失败 } override fun onResponse(call: Call, response: Response) { val inputStream: InputStream = response.body?.byteStream() ?: return // 保存文件并更新下载进度 val totalSize: Long = response.body?.contentLength() ?: -1 var downloadedSize: Long = 0 val outputStream = FileOutputStream("/storage/emulated/0/Download/file.zip") val buffer = ByteArray(8192) while (true) { val bytes = inputStream.read(buffer) if (bytes == -1) break outputStream.write(buffer, 0, bytes) downloadedSize += bytes val progress = (downloadedSize * 100 / totalSize).toInt() listener.onDownloadProgress(progress) } outputStream.close() inputStream.close() // 下载完成 } }) ``` 注意,这段代码中保存文件的路径是硬编码的,你需要根据实际需求修改它。另外,为了更新 UI,我们需要在 onDownloadProgress 方法中使用 runOnUiThread 方法,以确保在主线程中执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值