Android核心技术-day04-01-网络图片查看器(安卓消息循环机制)

版权声明:心灵泽尘 https://blog.csdn.net/github_38313789/article/details/83757051

package com.gaozewen.netimageviewer;

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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final int LOAD_IMAGE = 1;
    private static final int LOAD_ERROR = 2;
    private ImageView iv;
    private List<String> paths;
    private int currentPosition = 0;
    // UIThread 主线程 ↓
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case LOAD_IMAGE:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    iv.setImageBitmap(bitmap);
                    Toast.makeText(MainActivity.this,"加载图片成功", Toast.LENGTH_SHORT).show();
                    break;
                case LOAD_ERROR:
                    Toast.makeText(MainActivity.this,"加载图片失败", Toast.LENGTH_SHORT).show();
                    break;
            }
            return true;
        }
    });

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

        iv = (ImageView) findViewById(R.id.iv);
        // 1.链接服务器,获取所有的图片链接信息
        loadAllImagePath();
    }

    // 获取全部图片资源路径
    private void loadAllImagePath() {
        new Thread() {
            @Override
            public void run() {
                // 获取服务器数据
                try {
                    URL url = new URL("http://192.168.1.102:8080/img/gaga.html");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET"); // 注意 GET 请求必须大写
                    int code = conn.getResponseCode();
                    if (code == 200) { // 返回成功
                        InputStream is = conn.getInputStream();
                        File file = new File(getCacheDir(), "info.txt");
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                        fos.flush();
                        fos.close();
                        is.close();

                        beginLoadImage();
                    } else if (code == 404) {
                        Message msg = Message.obtain();
                        msg.what = LOAD_ERROR;
                        msg.obj = "获取html失败,返回码:" + code;
                        mHandler.sendMessage(msg);
                    }else {
                        Message msg = Message.obtain();
                        msg.what = LOAD_ERROR;
                        msg.obj = "服务器异常,返回码:" + code;
                        mHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    // 开始加载图片,在从服务器获取完毕图片资源路径之后执行
    private void beginLoadImage() {
        try {
            paths = new ArrayList<>();
            File file = new File(getCacheDir(), "info.txt");
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String line;
            while ((line = br.readLine()) != null) {
                paths.add(line);
            }
            br.close();
            fis.close();

            loadImageByPath(paths.get(currentPosition));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //
    private void loadImageByPath(final String path) {
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = new File(getCacheDir(), path.replace("/", "") + ".jpg");
                    if (file.exists() && file.length() > 0){ // 缓存中有文件
                        System.out.println("通过缓存把图片获取出来...");

                        Message msg = Message.obtain();
                        msg.what = LOAD_IMAGE;
                        msg.obj = BitmapFactory.decodeFile(file.getAbsolutePath());
                        mHandler.sendMessage(msg);

                        // 安卓消息循环机制
//                        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//                        iv.setImageBitmap(bitmap);
                        /**
                         * 创建子线程 消息循环!!!!
                         */
                        // UIThread 被创建之后就自带了一个 Looper,
                        // 这个 Looper 管理自身的 MessageQueue ,
                        // 其他创建出来的子线程 默认没有 Looper,
                        // 只能调用 Looper.prepare 和 Looper.loop 方法来进行消息循环
                        // 并且要 new 一个 Handler 对象来处理取出的 Message 对象
                        /*Looper.prepare();
                        mHandler = new Handler(){
                            @Override
                            public void handleMessage(Message msg) {
                                Toast.makeText(MainActivity.this,"加载图片完成" + msg.what, Toast.LENGTH_SHORT).show();
                            }
                        };
                        Message msg = Message.obtain();
                        msg.what = 100;
                        mHandler.sendMessage(msg);
                        Looper.loop();*/
                    }else { // 缓存中没文件
                        System.out.println("通过访问网络把图片资源获取出来...");
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        int code = conn.getResponseCode();
                        if(code == 200){
                            InputStream is = conn.getInputStream();
                            // 暂存在内存里的 图片
                            Bitmap bitmap = BitmapFactory.decodeStream(is);
                            // 将这个图片写入到 cache 文件夹中
                            FileOutputStream fos = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
                            fos.close();
                            is.close();

                            Message msg = Message.obtain();
                            msg.what = LOAD_IMAGE;
                            msg.obj = BitmapFactory.decodeFile(file.getAbsolutePath());
                            mHandler.sendMessage(msg);
                        }else {
                            /*Looper.prepare();
                            mHandler = new Handler(){
                                @Override
                                public void handleMessage(Message msg) {
                                    Toast.makeText(MainActivity.this,"获取失败", Toast.LENGTH_SHORT).show();
                                }
                            };
                            Looper.loop();*/
                            Message msg = Message.obtain();
                            msg.what = LOAD_ERROR;
                            msg.obj = "获取图片失败,返回码:" + code;
                            mHandler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = Message.obtain();
                    msg.what = LOAD_ERROR;
                    msg.obj = "获取图片失败,抛异常!!" ;
                    mHandler.sendMessage(msg);
                }
            }
        }.start();
    }

    public void pre(View view) {
        currentPosition--;
        if (currentPosition < 0){
            currentPosition = paths.size() -1;
        }
        loadImageByPath(paths.get(currentPosition));
    }

    public void next(View view) {
        currentPosition++;
        if (currentPosition >= paths.size()){
            currentPosition = 0;
        }
        loadImageByPath(paths.get(currentPosition));
    }
}

猜你喜欢

转载自blog.csdn.net/github_38313789/article/details/83757051