android 多线程

功能:下载网络图片,保存到本地

        下载图片,显示图片

        Handler Message 消息测试

参考:

API

http://www.cnblogs.com/shirley-1019/p/3557800.html

书籍:android 开发范例实践宝典

1. A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue.

package com.test.network;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    private EditText eUrlPath;

    private ImageView imageView;

    private Button btnNullMsg;

    private Button btndelayMessage;

    private Button btnRunnableMsg;

    private EditText editText;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                imageView.setImageBitmap((Bitmap) msg.obj);
            } else if (msg.what == 2) {
                Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        eUrlPath = (EditText) findViewById(R.id.eUrlPath);

        imageView = (ImageView) findViewById(R.id.imageView);

        btnNullMsg = (Button) findViewById(R.id.sendNullMessage);

        btndelayMessage = (Button) findViewById(R.id.btndelayMessage);

        btnRunnableMsg = (Button) findViewById(R.id.btnRunnableMsg);

        editText = (EditText) findViewById(R.id.editText);

        btnRunnableMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                editText.setText("RunnaleMessage");
                                Toast.makeText(MainActivity.this, "RunnalbeMessage", Toast.LENGTH_SHORT);
                            }
                        });
                    }
                }).start();
            }
        });
        btndelayMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        Message msg = Message.obtain();
                        msg.obj = "sendMessageDelayed";
                        mHandler.sendMessageDelayed(msg, 3000);
                    }
                }).start();
            }
        });
        btnNullMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = Message.obtain(mHandler);
                        msg.what = 3;
                        msg.obj = "sendToTarget";
                        msg.sendToTarget();
                    }
                }).start();
            }
        });
    }

    public void btnGetHttp(View view) {
        new Thread(new DownLoadImageThread()).start();

    }

    public void showImage(View view) {
        new Thread(new DownLoadImageBitMapThread()).start();
    }

    class DownLoadImageBitMapThread implements Runnable {

        @Override
        public void run() {
            //定义一个Message对象
            //Message msg = Message.obtain();
            Message message = mHandler.obtainMessage();
            HttpDownloader httpDownloader = new HttpDownloader();
            //String urlPath =eUrlPath.getText().toString();
            String urlPath = "http://img4.imgtn.bdimg.com/it/u=3340865222,3464212128&fm=21&gp=0.jpg";
            Bitmap bitmap = httpDownloader.getBitMapFromInput(urlPath);
            message.what = 1;
            message.obj = bitmap;

            mHandler.sendMessage(message);

        }
    }

    class DownLoadImageThread implements Runnable {


        @Override
        public void run() {
            //定义一个Message对象
            //Message msg = Message.obtain();
            Message message = mHandler.obtainMessage();
            HttpDownloader httpDownloader = new HttpDownloader();
            //String urlPath =eUrlPath.getText().toString();
            String urlPath = "http://img4.imgtn.bdimg.com/it/u=3340865222,3464212128&fm=21&gp=0.jpg";
            httpDownloader.downFile(urlPath, FileUtils.PATH, "test.jpg");
            message.what = 2;
            message.obj = "success";

            mHandler.sendMessage(message);

        }
    }


}

2. 使用 HttpDownloader 下载图片,处理流。

package com.test.network;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by 1 on 2016/4/12.
 */
public class HttpDownloader {


    public int downFile(String urlPath, String path, String fileName) {

        InputStream inputStream = getInputStream(urlPath);
        if (inputStream != null) {
            FileUtils.write2SDFromInput(inputStream, path, fileName);
        }

        return 0;
    }

    public Bitmap getBitMapFromInput(String pathUrl) {
        InputStream inputStream = getInputStream(pathUrl);
        return BitmapFactory.decodeStream(inputStream);
    }

    public InputStream getInputStream(String pathUrl) {

        InputStream inputStream = null;
        try {
            URL url = new URL(pathUrl);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setConnectTimeout(50000);
            urlConnection.connect();

            inputStream = urlConnection.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }
}
View Code

3. 文件处理

package com.test.network;

import android.os.Environment;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * Created by 1 on 2016/4/12.
 */
public class FileUtils {

    public static String PATH = Environment.getExternalStorageDirectory() + "/00DownLoad/";

    public static boolean isFileExist(String fileName) {
        File file = new File(fileName);
        return file.exists();
    }

    public static void createDir(String path) {

        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

    }

    public static void createFile(String path, String fileName) {
        File file = new File(path + fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void write2SDFromInput(InputStream inputStream, String path, String fileName) {

        //创建目录
        createDir(path);
        //创建文件
        createFile(path, fileName);

        File file = new File(path + fileName);
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            while ((inputStream.read(buffer)) != -1) {
                outputStream.write(buffer);
            }
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {

            }
        }

    }
}
View Code
原文地址:https://www.cnblogs.com/newlangwen/p/5387267.html