Android进阶之动态加载图片(runOnUiThread/handler)

1、权限

 <!-- 访问服务器权限 -->
 <uses-permission android:name="android.permission.INTERNET" />

2、activity_image_view.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.guan.http.activity.ImageViewActivity" >

    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/handler"
        android:contentDescription="@string/abc_action_bar_home_description"/>

</RelativeLayout> 

3、UserService.java

package com.guan.http.service;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import android.graphics.Bitmap;
import com.guan.http.model.Student;

public interface UserService {

    public Bitmap getImage() throws Exception;
}

4、UserServiceImpl.java

package com.guan.http.service;

public class UserServiceImpl implements UserService {

    /** * 获取图片业务 */
    @Override
    public Bitmap getImage() throws Exception {
        Bitmap bitmap = null;
        InputStream in = null;
        URL url = null;
        HttpURLConnection urlConnection = null;
        OutputStream out = null;
        byte[] data = null;

        try {
            /** * Post方法 */
            Map<String, String> params = new HashMap<String, String>();
            params.put("id", "1");
            // 封装参数
            data = setPostPassParams(params).toString().getBytes();

            url = new URL(Constant.uri + "GetImageServlet");
            // 打开连接
            urlConnection = (HttpURLConnection) url.openConnection();
            // 设置连接超时时间
            urlConnection.setConnectTimeout(3000);
            // 设置响应超时时间
            urlConnection.setReadTimeout(3000);
            // 设置可以读取数据
            urlConnection.setDoInput(true);
            // 设置可以写数据
            urlConnection.setDoOutput(true);
            // 设置请求方法时POST请求
            urlConnection.setRequestMethod("POST");
            // 设置缓冲
            urlConnection.setUseCaches(false);

            /** * HTTP协议 */
            // urlConnection.setRequestProperty("Content-Type", newValue);
            // urlConnection.setRequestProperty("Content-Length", newValue);

            // 连接
            urlConnection.connect();
            // 输出流、客户端向服务器发送数据
            out = urlConnection.getOutputStream();
            // 向服务器写数据的关键代码
            out.write(data);
            // 刷新
            out.flush();

            // 响应状态
            int response = urlConnection.getResponseCode();
            if (response != HttpURLConnection.HTTP_OK) {
                throw new ServiceRulesException("请求服务器出错");
            }
            // 服务器传给客户端
            in = new BufferedInputStream(urlConnection.getInputStream());
            if (in != null) {
                // 转化类型 InputStream --> Bitmap 操作图片流的工厂方法
                // 其他的转化: InputStream Bitmap Drawable byte[]
                bitmap = BitmapFactory.decodeStream(in);
            } 

            /** * Get方法 */
            // url = new URL(Constant.uri + "GetImageServlet?id=1");
            // // 打开连接
            // urlConnection = (HttpURLConnection) url.openConnection();
            // // 设置可以读取
            // urlConnection.setDoInput(true);
            // // 设置请求类型
            // urlConnection.setRequestMethod("GET");
            // // 连接
            // urlConnection.connect();
            // // 响应状态
            // int response = urlConnection.getResponseCode();
            // if (response != HttpStatus.SC_OK) {
            // throw new ServiceRulesException("请求服务器出错");
            // }
            //
            // in = urlConnection.getInputStream();
            // if(in != null) {
            // // 转化类型 InputStream --> Bitmap 操作图片流的工厂方法
            // // 其他的转化: InputStream Bitmap Drawable byte[]
            // bitmap = BitmapFactory.decodeStream(in);
            // }
        } finally {
            if (in != null) {
                in.close();
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

        return bitmap;
    }

    // 静态方法,重复使用
    /** * @description 构造Post参数传递 * @param params * @return * @throws UnsupportedEncodingException */
    private static StringBuffer setPostPassParams(Map<String, String> params)
            throws UnsupportedEncodingException {

        StringBuffer stringBuffer = new StringBuffer();

        for (Map.Entry<String, String> entry : params.entrySet()) {
            stringBuffer.append(entry.getKey()).append("=")
                    .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                    .append("&");
        }

        // 把最后&去掉
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);

        return stringBuffer;
    }
}

5、ImageViewActivity.java

package com.guan.http.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;

import com.guan.http.R;
import com.guan.http.exception.ServiceRulesException;
import com.guan.http.service.UserService;
import com.guan.http.service.UserServiceImpl;

public class ImageViewActivity extends BaseActivity {

    private ImageView mImage;
    private UserService userService;

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

        /** * 初始化变量 */
        initVariable();
        /** * 线程 */
        thread();
    }

    /** * 初始化变量 */
    private void initVariable() {
        mImage = (ImageView) findViewById(R.id.iv_image);
        userService = new UserServiceImpl();
    }

    /** * 线程 */
    private void thread() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    // 获取图片bitmap对象
                    final Bitmap bitmap = userService.getImage();

                    // runOnUiThread类似于Handler的方法
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            if (bitmap != null) {
                                mImage.setImageBitmap(bitmap);
                            } else {
                                // 代码指定控件加载图片两方法
                                mImage.setImageResource(R.drawable.ic_launcher);
                                mImage.setImageDrawable(getResources()
                                        .getDrawable(R.drawable.ic_launcher));
                            }
                        }
                    });

                } catch (final ServiceRulesException e) {
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showMsg(e.getMessage());
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showMsg("获取服务器出错");
                        }
                    });
                }
            }
        }).start();
    }
}

6、BaseActivity.java

package com.guan.http.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.view.Window;
import android.widget.Toast;

/** * @author Guan * @file com.example.guan.activity * @date 2015/8/14 * @Version 1.0 */
public class BaseActivity extends Activity {

    public final static int FIAL_LOAD_IMAGE = 1;
    public final static int FLAG_STUDENT_SUCCCESS = 1;
    public final static int FLAG_LOGIN_SUCCCESS = 1;
    public final static int FLAG_REGISTER_SUCCCESS = 1;
    public final static String MSG_LOGIN_ERROR = "登录出错";
    public final static String MSG_LOGIN_SUCCESS = "登录成功";
    public final static String MSG_LOGIN_FAILED = "登录名|登录密码错误";
    public final static String MSG_SERVER_ERROR = "请求服务器错误";
    public final static String MSG_REQUEST_TIMEOUT = "请求服务器超时";
    public final static String MSG_REPONSE_TIMEOUT = "服务器响应超时";
    public final static String MSG_STUDENT_ERROR = "加载数据出错";
    public final static String MSG_REGISTER_ERROR = "注册出错";
    public final static String MSG_REGISTER_SUCCESS = "注册成功";
    public final static String MSG_REGISTER_FAILED = "注册名|注册密码错误";

    /** * 把与业务相关的系统框架、界面初始化、设置等操作封装 * * @param savedInstanceState */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    /** * Toast公共方法 * @param pMsg */
    public void showMsg(String pMsg) {
        Toast.makeText(BaseActivity.this, pMsg, Toast.LENGTH_SHORT).show();
    }

    /** * intent 跳转Activity公共方法 */
    public void openActivity(Class<?> pClass) {

        Intent _intent = new Intent(this,pClass);
        startActivity(_intent);
    }

    /** * intent startActivityForResult 打开系统加载图片 */
    public void startActivityForResult() {
        Intent intent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent,FIAL_LOAD_IMAGE);
    }

    /** * dialog 对话框公共方法 */
    public void showAlterDialog() {

    }

}

7、效果图

Android进阶之动态加载图片(runOnUiThread/handler)_第1张图片

你可能感兴趣的:(Android进阶之动态加载图片(runOnUiThread/handler))