Handler异步下载文件以及更新进度条

   日期:2020-09-08     浏览:103    评论:0    
核心提示:异步下载文件的代码如下import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.ProgressBar;import java.io.File;import java.io.FileOu

异步下载文件的代码如下

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DownloadActivity extends Activity {

private Handler mHandler;
public static final int DOWNLOAD_MESSAGE_CODE = 100001;
public static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_download);

    final ProgressBar progressBar = (ProgressBar)findViewById(R.id.progressBar);

    

    findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                //这个地方调用下边的download方法
                    download("http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk");
                }
            }).start();

        }
    });

    mHandler =  new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case DOWNLOAD_MESSAGE_CODE:
                    if(msg.obj!=null)
                    progressBar.setProgress((Integer) msg.obj);
                    break;
                case DOWNLOAD_MESSAGE_FAIL_CODE:


            }
        }
    };
}
    private void download(String appUrl){
        try {
            URL url = new URL(appUrl);
            URLConnection urlConnection = url.openConnection();
				//io来读取文件
            InputStream inputStream = urlConnection.getInputStream();

            
            int contentLength = urlConnection.getContentLength();

            String downloadFolderName = Environment.getExternalStorageDirectory()
                    + File.separator+"imooc"+File.separator;

            File file = new File(downloadFolderName);
            if (!file.exists()){
                file.mkdir();
            }

            String fileName = downloadFolderName + "imooc.apk";

            File apkFile = new File(fileName);

            if (apkFile.exists()){
                apkFile.delete();
            }

            int downloadSize = 0;
            byte[] bytes = new  byte[1024];

            int length = 0;

            OutputStream outputStream = new FileOutputStream(fileName);
            while ((length = inputStream.read(bytes)) != -1){
            
            //参数为public void write(byte[] b,int off,int len):写一个字节数组的一部分

                outputStream.write(bytes,0,length);
                downloadSize += length;
                

                Message message = Message.obtain();
                message.obj = downloadSize * 100 / contentLength;
                message.what = DOWNLOAD_MESSAGE_CODE;
                mHandler .sendMessage(message);
            }
            inputStream.close();
            outputStream.close();





        }catch (MalformedURLException e){
            notifyDownloadFaild();
            e.printStackTrace();
        }catch (IOException e){
            notifyDownloadFaild();
            e.printStackTrace();
        }
}

private  void  notifyDownloadFaild(){
    Message message = Message.obtain();
    message.what = DOWNLOAD_MESSAGE_FAIL_CODE;
    mHandler .sendMessage(message);
}
}

文件的读取要用到的知识有io流,以及刚刚学习的Handler的用法。
其中download的代码部分需要好好理解。

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服