【Android】结合AsyncTask和第三方Okhttp的Service的项目-展示图片下载demo(附源码)

Demo基本功能展示

请添加图片描述

具体过程

思路

  • 服务下载图片
  • 调用图片
  • UI 串连
  • 网络okhttp
  implementation 'com.squareup.okhttp3:okhttp:3.10.0'

代码

xml视图代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:gravity="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:context="MainActivity">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="点我捆绑下载"
            />

        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/button"
            android:layout_centerInParent="true"
            android:text="还没开始加载!" />

        <ProgressBar
            android:id="@+id/progress_bar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/text"
            android:max="100"
            android:progress="0" />

        <Button
            android:id="@+id/cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/progress_bar"
            android:layout_centerInParent="true"
            android:text="不展示图片" />
    </RelativeLayout>

    <ImageView
        android:id="@+id/iv_picture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/relativeLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>

服务的代码

  • 监听类
package com.chris.servicedownloadpictest;

public interface DownloadListener {
   void processDownload(int i);
   void success();
   void failure();
}

  • AsyncTask 多线程异步处理
package com.chris.servicedownloadpictest;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyDownloadAsyncTask extends AsyncTask<String,Integer,Boolean> {

    public static String  filePath = "";
    public static Bitmap loadBitmap;
    // 下载成功
    public static final int TYPE_SUCCESS = 0;
    // 下载失败
    public static final int TYPE_FAILED = 1;
    // 下载暂停
    public static final int TYPE_PAUSED = 2;
    // 下载取消
    public static final int TYPE_CANCELED = 3;
    // 下载状态监听回调
    private DownloadListener listener;
    // 是否取消
    private boolean isCancelled = false;
    // 是否暂停
    private boolean isPaused = false;
    // 当前进度
    private int lastProgress;

    public MyDownloadAsyncTask(DownloadListener downloadListener) {
        this.listener = downloadListener;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    /**
     *   文件下载使用到第三方的okhttp
     */
    @Override
    protected Boolean doInBackground(String... strings) {

        // 文件输入流
        InputStream is = null;
        RandomAccessFile accessFile = null;
        File file = null;
        // 记录已下载的文件长度
        long downloadedLength = 0;
        // 获取下载的URL地址
        String downloadUrl = strings[0];
        // 从URL下载地址中截取下载的文件名
        String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
        // 获取SD卡的Download 目录
        String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
        //  得到要保存的文件
        filePath = directory + fileName;
        file = new File(filePath);
        // 如果文件已经存在  获取文件的长度
        if (file.exists()) {
            downloadedLength = file.length();
        }
        try {
            //   获取待下载文件的字节长度
            long contentLength = getContentLength(downloadUrl);
            //  如果待下载文件的字节长度为0 说明待下载文件有问题
            if (contentLength == 0) {
                return false;
            } else if (contentLength == downloadedLength) {
                //   已下载字节和文件总字节相等 说明已经下载完了
                return true;
            }
            //  获取OkHttpClient 对象
            OkHttpClient client = new OkHttpClient();
            //  创建请求
            Request request = new Request.Builder()
                    //  断点下载,指定从哪个字节开始下载
                    .addHeader("RANGE", "bytes=" + downloadedLength + "-")
                    // 设置下载地址
                    .url(downloadUrl)
                    .build();
            //  获取响应
            Response response = client.newCall(request).execute();
            if (response != null) {
                // 读取服务器响应的数据
                is = response.body().byteStream();
                // 获取随机读取文件类  可以随机读取一个文件中指定位置的数据
                accessFile = new RandomAccessFile(file, "rw");
                // 跳过已下载的字节
                accessFile.seek(downloadedLength);
                //指定每次读取文件缓存区的大小为1KB
                byte[] b = new byte[1024];
                int total = 0;
                int len;
                //   每次读取的字节长度
                while ((len = is.read(b)) != -1) {
                        // 读取的全部字节的长度
                        total += len;
                        // 写入每次读取的字节长度
                        accessFile.write(b, 0, len);
                        // 计算已下载的百分比
                        int progress = (int) ((total + downloadedLength) * 100 / contentLength);
                        // 更新进度条
                        publishProgress(progress);
                }
                // 关闭连接  返回成功
                response.body().close();
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭输入流
                if (is != null) {
                    is.close();
                }
                // 关闭文件
                if (accessFile != null) {
                    accessFile.close();
                }
                Log.d("TAG", "这里永远都会执行 ");
                // 如果是取消的  就删除掉文件
                if (isCancelled && file != null) {
                    file.delete();
                }
                FileInputStream fileInputStream = new FileInputStream(filePath);
                loadBitmap = BitmapFactory.decodeStream(fileInputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 辅助类工具类,但是我觉得这样写并不是很好,应该一个网络连接即可,又构造一个浪费时间!!后续可以改改
     * @param downloadUrl
     * @return
     * @throws IOException
     */
    private long getContentLength(String downloadUrl) throws IOException {
        // 获取OkHttpClient
        OkHttpClient client = new OkHttpClient();
        // 创建请求
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        //  获取响应
        Response response = client.newCall(request).execute();
        //  如果响应是成功的话
        if (response != null && response.isSuccessful()) {
            // 获取文件的长度  清除响应
            long contentLength = response.body().contentLength();
            response.close();
            return contentLength;
        }
        return 0;
    }


    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        listener.processDownload(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if(aBoolean){
            listener.success();
        }else{
            listener.failure();
        }
    }
}

  • MyService
package com.chris.servicedownloadpictest;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;

public class MyService extends Service {
    private MyDownloadAsyncTask downloadTask;
    private MyBinder myBinder = new MyBinder();

    public MyService() {
    }

    public class MyBinder extends Binder{
        void startDownload(String url ,DownloadListener listener){
            downloadTask = new MyDownloadAsyncTask(listener);
            downloadTask.execute(url);
        }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }
}

Activity

package com.chris.servicedownloadpictest;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DownloadManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.net.URL;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button button;
    private TextView text;
    private ProgressBar progressBar;
    private Button cancel;
    private ImageView ivPicture;

    private DownloadListener listener;
    private MyService.MyBinder binder;
    private MyService service;
    //可以更换
    final static String URL_STRING = "https://developer.android.google.cn/images/service_lifecycle.png";
    //            "https://img-blog.csdnimg.cn/img_convert/f538b09600741dd31645d1ad32dc0105.png";
//            "http://n1.itc.cn/img8/wb/recom/2016/04/26/146164046862104328.JPEG";
    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            binder = (MyService.MyBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        initListener();
        initService();
    }

    private void initService() {
        // 点击进行捆绑和操作
        Intent intent = new Intent(MainActivity.this,MyService.class);
        bindService(intent,serviceConnection,BIND_AUTO_CREATE);
    }

    private void startDownload() {
        binder.startDownload(URL_STRING,listener);
    }

    private void initListener() {
        listener = new DownloadListener() {
            @Override
            public void processDownload(int i) {
                text.setText(String.valueOf(i));
                progressBar.setProgress(i);
            }

            @Override
            public void success() {
                //成功就设置图片
                ivPicture.setImageBitmap(MyDownloadAsyncTask.loadBitmap);
                text.setText("下载成功");
            }

            @Override
            public void failure() {
                //失败就展示失败的文字
                text.setText("Download fail");
            }
        };
    }

    private void initViews() {
        button = findViewById(R.id.button);
        text = findViewById(R.id.text);
        progressBar = findViewById(R.id.progress_bar);
        cancel = findViewById(R.id.cancel);
        ivPicture = findViewById(R.id.iv_picture);
        button.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }
   static Boolean isCancel = false;
    @Override
    public void onClick(View view) {
        switch(view.getId()) {

            case R.id.button:
                startDownload();
                break;
            case R.id.cancel:
                // 图片取消
                if(!isCancel){
                    ivPicture.setVisibility(View.INVISIBLE);
                    cancel.setText("展示图片");
                    isCancel = true;
                }else {
                    ivPicture.setVisibility(View.VISIBLE);
                    cancel.setText("不展示图片");
                    isCancel = false;
                }

                break;
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值