Android中使用Kotlin协程(Coroutines)和Retrofit进行网络请求(二)之文件下载

  • 写在前面
    下载功能是非常常用的功能,今天我们要通过kotlin协程和retrofit来是实现文件下载的功能.retorfit本身可以将请求结果以InputStream的形式返回,拿到InputStream,我们再将数据写入文件的outputStream,就可以实现文件的下载了.在java时我们也是这么做的.但问题是,我们在IO操作时都是在子线程操作,而下载过程中我还需要在UI显示下载状态,所以在java的方式中我们一般需要通过listener回调的方式来更新UI.我们在上一篇文章中看到,使用kotlin协程和retrofit进行网络请求并没有用回调,而且代码和rxjava一样简洁.下面来通过一个小demo来看看如何使用协程和retrofit进行网络下载.

  • 项目配置
    项目配置参见上篇文章

  • 代码实现
    话不多说先上图
    在这里插入图片描述
    布局代码如下:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <EditText
            android:id="@+id/et_url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginTop="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            android:text="http://i3.3conline.com/images/piclib/201112/06/batch/1/119786/1323168166282kf5i4y67qh.jpg"
            tools:ignore="Autofill,LabelFor,TextFields" />
    
        <Button
            android:id="@+id/btn_down"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值