消息反射机制

  • Handler Message
  • AsyncTask


Handler Message

package com.application.picturedownload;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

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

public class MainActivity extends Activity implements View.OnClickListener{

    private Button downloadImage;
    private Button showImage;
    private EditText imageAddress;
    private ImageView image;

    private Handler mHandler= new Handler(){

        @Override
        public void handleMessage(Message msg) {
            String imgPath = (String) msg.obj;
            Bitmap bitMap = BitmapFactory.decodeFile(imgPath);
            image.setImageBitmap(bitMap);
        }
    };



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

        downloadImage = (Button)findViewById(R.id.download);
        showImage = (Button)findViewById(R.id.show_image);
        imageAddress = (EditText) findViewById(R.id.download_address);
        image = (ImageView) findViewById(R.id.image);

        downloadImage.setOnClickListener(this);
        showImage.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.download:
                Thread thread = new Thread(new DownloadImageThread(imageAddress.getText().toString()));
                thread.start();

                break;
            case R.id.show_image:
                ShowImageThread showImageThread = new ShowImageThread(mHandler);
                new Thread(showImageThread).start();

                break;
            default:
                break;
        }
    }


    class DownloadImageThread implements Runnable{

        private String address;

        public DownloadImageThread(String address){
            this.address = address;
        }

        @Override
        public void run() {

            try {
                URL url = new URL(address);
                HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
                urlConnection.setConnectTimeout(5000);
                urlConnection.setDoInput(true);
                urlConnection.setRequestMethod("GET");
                InputStream in =  urlConnection.getInputStream();
                File imgPath = new File(Environment.getExternalStorageDirectory(),"shuidaosuo.jpg");
                FileOutputStream out = new FileOutputStream(imgPath.getAbsoluteFile());
                int len = -1;
                byte[] bytes = new byte[1024];
                while((len = in.read(bytes)) != -1){
                    out.write(bytes,0,len);
                }

                in.close();
                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }




    }



    class ShowImageThread implements Runnable{

        private Handler handler;

        ShowImageThread(Handler handler){
            this.handler = handler;
        }

        @Override
        public void run() {
            Message msg = handler.obtainMessage();
            File file = new File(Environment.getExternalStorageDirectory(),"download.jpg");
            String imgPath = file.getAbsolutePath();
            msg.obj = imgPath;
            handler.sendMessage(msg);
        }
    }

}

消息反射机制_第1张图片
消息反射机制_第2张图片



AsyncTask

  • AsyncTask是对Handler消息反射机制的很好封装
  • AsyncTask接受三个参数,第一个为输入参数,第二个为进度条,第三个为结果。
    doInBackground( )函数是运行在子线程中的,线程已经系统开辟好了,无需我们创建,onPostUpdate( )函数里面内容是运行在UI线程即主线程当中的

例子:实现网页下载,并显示到UI线程中。

MainActivity.java

package com.example.asynctaskdemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;


public class MainActivity extends Activity implements View.OnClickListener {

    private Button execute;
    private Button cancel;
    private ProgressBar progressBar;
    private TextView textView;


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

        execute = (Button) findViewById(R.id.execute);
        cancel = (Button) findViewById(R.id.cancel);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        textView = (TextView) findViewById(R.id.text_view);

        execute.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        DownloadTask downloadTask = new DownloadTask(progressBar,textView);
        switch (v.getId()){
            case R.id.execute:
                downloadTask.execute("http://blog.csdn.net/wiseclown/article/details/50992507");
                execute.setEnabled(false);
                cancel.setEnabled(true);
                break;
            case R.id.cancel:
                downloadTask.cancel(true);
                execute.setEnabled(true);
                cancel.setEnabled(false);
                break;
            default:
                break;
        }
    }
}



DownloadTask.java

package com.example.asynctaskdemo;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/** * Created by Administrator on 2016/3/28. */
public class DownloadTask extends AsyncTask<String,Integer,String> {

    private ProgressBar progressBar;
    private TextView textView;

    public DownloadTask(ProgressBar progressBar,TextView textView){
        this.progressBar = progressBar;
        this.textView = textView;
    }

    @Override
    protected String doInBackground(String... params) {

        Log.d("TAG","doInBackground begin");

        StringBuilder builder = new StringBuilder();
        try {
            URL url = new URL(params[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            if(urlConnection == null){
                Log.d("TAG","urlConnection failed");
            }

            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(5000);
            urlConnection.setDoInput(true);

            urlConnection.setRequestProperty("Accept-Encoding", "identity");

            InputStream in = urlConnection.getInputStream();
            long total = urlConnection.getContentLength();

            /*BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String buf; while((buf = reader.readLine()) != null){ builder.append(buf); publishProgress((int)((builder.length() / (float)total) * 100)); } reader.close();*/

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while( (len = in.read(bytes) ) != -1 ){
                byteArrayOutputStream.write(bytes,0,len);
                publishProgress( (int)(byteArrayOutputStream.size() / (float)total)*100 );
            }

            return  new String(byteArrayOutputStream.toByteArray());

        } catch (Exception e) {
            e.printStackTrace();
        }

       Log.d("TAG","doInBackground end");

       // return builder.toString();

        return null;

    }

    @Override
    protected void onProgressUpdate(Integer... values) {

        Log.d("Total capacity:",values[0]+"");
        int value = values[0];
        progressBar.setProgress(value);

    }

    @Override
    protected void onPostExecute(String s) {
        textView.setText(s);
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        progressBar.setProgress(0);
        textView.setText("");
    }
}

你可能感兴趣的:(消息反射机制)