Handler通信(二)

本文主要实现的是Handler通信下载文件并更新进度条。

主要思路:

主线程——点击按钮——发起下载——开启子线程做下载——下载过程中通知主线程——主线程更新进度条

该说不说,上代码!

activity_download代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button2"/>

    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:max="100"
        android:layout_gravity="center_horizontal"/>



主线程写download,并创建方法:

@Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        download(APP_URL);
                    }
                }).start();

            }
        });

子线程下载程序如下:

private void download(String appUrl) {

        try {
            URL   url = new URL(appUrl);//创建对象
            URLConnection urlConnection= url.openConnection();//打开连接

            InputStream inputStream=urlConnection.getInputStream();//获取数据流

            int contentLength=urlConnection.getContentLength();//获取文件总长度

            String downloadFolderName= Environment.getExternalStorageDirectory()
                    + File.separator+"imooc"+File.separator;//开始下载folder,然后放在SDK目录下面的imooc目录下

            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){
                outputStream.write(bytes,0,length);
                downloadSize +=length;
                /*
                  update UI
                 */
                Message message=Message.obtain();
                message.obj=downloadSize*100/contentLength;
                message.what=DOWNLOAD_MESSAGE_CODE;
                mHandler.sendMessage(message);//handler用来发送信息
            }
            inputStream.close();
            outputStream.close();

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

    }

使用handler传递信息:

mHandler.sendMessage(message);//handler用来发送信息

创建handler:

mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case DOWNLOAD_MESSAGE_CODE:
                        progressBar.setProgress((Integer) msg.obj);

                        break;
                }
            }
        };

收到相应后,进度条开始更新!

完整的代码如下:

package com.example.handlerproject;

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 androidx.annotation.Nullable;

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 {
    public static final int DOWNLOAD_MESSAGE_CODE = 100001;
    private static final int DOWNLOAD_MESSAGE_FAIL_CODE = 100002;
    public static final String APP_URL = "http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk";
    private Handler mHandler;
    @Override
    protected void onCreate(@Nullable 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(APP_URL);
                    }
                }).start();

            }
        });
            mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case DOWNLOAD_MESSAGE_CODE:
                        progressBar.setProgress((Integer) msg.obj);

                        break;
                }
            }
        };

    }

    private void download(String appUrl) {

        try {
            URL   url = new URL(appUrl);//创建对象
            URLConnection urlConnection= url.openConnection();//打开连接

            InputStream inputStream=urlConnection.getInputStream();//获取数据流

            int contentLength=urlConnection.getContentLength();//获取文件总长度

            String downloadFolderName= Environment.getExternalStorageDirectory()
                    + File.separator+"imooc"+File.separator;//开始下载folder,然后放在SDK目录下面的imooc目录下

            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){
                outputStream.write(bytes,0,length);
                downloadSize +=length;
                /*
                  update UI
                 */
                Message message=Message.obtain();
                message.obj=downloadSize*100/contentLength;
                message.what=DOWNLOAD_MESSAGE_CODE;
                mHandler.sendMessage(message);//handler用来发送信息
            }
            inputStream.close();
            outputStream.close();

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

    }
}

Handler通信(三)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值