Android中AsyncTask异步处理

有三个异步处理优

1 runOnUiThread

             runOnUiThread(new Thread(){
               @Override
                  public void run() {
                        tx.setText(bs.toString());
                  }
                });

2 Handler

 Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
}
}

3.AsyncTask

package com.example.wangye.androidgj_class6;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    Button bt,btCancel;
    TextView tx;
    MyTask myTask;
    ProgressBar pb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
    public void init(){
        bt = (Button) findViewById(R.id.button);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myTask = new MyTask();
                //启动任务
                pb.setMax(100);
                pb.setProgress(0);
                //写要执行的网址
                myTask.execute("http://192.168.56.1:8080/my1710.apk");
            }
        });
        tx = (TextView) findViewById(R.id.textView);
        pb = (ProgressBar) findViewById(R.id.progressBar);

        btCancel = (Button) findViewById(R.id.button2);
        btCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myTask.cancel(true);
            }
        });
    }
//泛型1  联网所需数据   泛型2  下载进度  泛型3 下载结果
    class MyTask extends AsyncTask{
        @Override//联网前更新UI   顺序1
        protected void onPreExecute() {
            tx.setText("即将开始下载...");
        }
        @Override//联网  顺序2
        protected String doInBackground(String... strings) {
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setConnectTimeout(10000);
                con.setReadTimeout(10000);
                con.connect();
                if(con.getResponseCode() == 200){
                    InputStream is = con.getInputStream();
                    //获取当前需要下载的数据的总长度
                    int total = con.getContentLength();
                    int now = 0;
                    File file = new File(Environment.getExternalStorageDirectory()+"/test1710.apk");
                    FileOutputStream fs = new FileOutputStream(file);
                    byte buffer[] = new byte[512];
                    int length = -1;
                    while(  (length = is.read(buffer)) != -1 ){
                        fs.write(buffer,0,length);
                        //累计下载数据的长度
                        now += length;// now = now + length;
                        publishProgress( (int) ( now / (float)total * 100 ) );
                        fs.flush();
                    }
                    is.close();
                    fs.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "下载已经完成";
        }
        @Override//联网过程中 更新进度UI    顺序2
        protected void onProgressUpdate(Integer... values) {
            tx.setText("当前下载进度:"+values[0]+"%");
            //给进度条设置进度
            pb.setProgress(values[0]);
        }
        @Override//联网结束后更新UI   顺序3
        protected void onPostExecute(String s) {
            tx.setText(s);
        }



        @Override//联网过程中 取消联网   不在顺序里  需要手动调用
        protected void onCancelled() {
            tx.setText("取消下载");
        }


    }


}

加载进度

 File file = new File(Environment.getExternalStorageDirectory()+"/test1710.apk");
                    FileOutputStream fs = new FileOutputStream(file);
                    byte buffer[] = new byte[512];
                    int length = -1;
                    while(  (length = is.read(buffer)) != -1 ){
                        fs.write(buffer,0,length);
                        //累计下载数据的长度
                        now += length;// now = now + length;
                        publishProgress( (int) ( now / (float)total * 100 ) );
                        fs.flush();
                    }
                    is.close();
                    fs.close();

你可能感兴趣的:(Android中AsyncTask异步处理)