Handler是一种异步回调机制,主要负责与子线程进行通信。
– Handler机制主要包括四个关键对象:
• Message:消息,它由MessageQueue统一列队,由Handler处理。
• Handler:处理者,主要负责Message的发送以及处理。
• MessageQueue:消息队列,主要用来存放Handler发送过来的消息, 并且按照先入先出的规则执行。
• Looper:消息循环,不断的从MessageQueue中抽取Message并执行。
MainActivity页面
public class MainActivity extends AppCompatActivity {
protected static final int CHANGE_UI = 1;
protected static final int ERROR = 2;
private EditText et_path;
private ImageView iv_pic;
//主线程创建消息处理器
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what==CHANGE_UI){
Bitmap bitmap=(Bitmap)msg.obj;//取图片
iv_pic.setImageBitmap(bitmap);
}else if (msg.what==ERROR){
Toast.makeText(MainActivity.this, "图片显示错误", Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
iv_pic = (ImageView) findViewById(R.id.iv_pic);
}
public void click(View view) {
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)){
Toast.makeText(this, "路径不存在", Toast.LENGTH_SHORT).show();
}else {
//开启子线程
new Thread(){
private HttpURLConnection conn;
private Bitmap bitmap;
public void run() {
try {
URL url = new URL(path);
conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(50000);//请求失效时间
int code=conn.getResponseCode();//获取响应代码。200/505...
if(code==200){
InputStream is=conn.getInputStream();
bitmap= BitmapFactory.decodeStream(is);
Message msg=new Message();
msg.what=CHANGE_UI;
msg.obj=bitmap;
handler.sendMessage(msg);
}else {
Message msg=new Message();
msg.what=ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg=new Message();
msg.what=ERROR;
handler.sendMessage(msg);
}
}
}.start();
}
}
}