(1)主线程创建时,系统会同时创建消息队列对象(MessageQueue)和消息轮询器对象(Looper)
(2)轮询器的作用,就是不停的检测消息队列中是否有消息(Message)
(3)消息队列一旦有消息,轮询器会把消息对象传给消息处理器(Handler),处理器会调用handleMessage方法来处理这条消息,handleMessage方法运行在主线程中,所以可以刷新ui
总结:
(1)只要消息队列有消息,handleMessage方法就会调用
(2)子线程如果需要刷新ui,只需要往消息队列中发一条消息,触发handleMessage方法即可(3) 子线程使用处理器对象的sendMessage方法发送消息
下面以下载图片做一个实例:
public class MainActivity extends Activity {
private static final String ADDRESS = "http://192.168.1.105:8080/g.jpg";
private static final int TIMEOUT = 5000;
private static ImageView iv;
private static MainActivity ma;
private static Handler handle = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
Bitmap bitmap = (Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
break;
case 0:
Toast.makeText(ma, "加载失败", 0).show();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
}
public void btnOnClicked(View v) {
// 首先判断图片文件在不在手机缓存里
final File file = new File(InternalStorageUtils.getInternalFilesDir(this), getFileName(ADDRESS));
if (file.exists()) {
Log.i("mtag", "图片已经存在");
Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());
iv.setImageBitmap(map);
} else {
// 开启子线程进行图片的下载以及缓存
new Thread() {
@Override
public void run() {
HttpURLConnection conn = null;
try {
URL url = new URL(ADDRESS);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT);
conn.setConnectTimeout(TIMEOUT);
conn.setRequestMethod("GET");
conn.connect();
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
// 保存到内部存储中
InternalStorageUtils.saveFileToInternalFilesDir(MainActivity.this,
readFromStream(conn.getInputStream()), getFileName(ADDRESS));
// 第一次读完后InputStreame里没有数据了
Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg = handle.obtainMessage();
msg.obj = map;
msg.what = 1;
handle.sendMessage(msg);
} else {
Message msg = handle.obtainMessage();
msg.what = 0;
handle.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
}
}.start();
}
}
// 将文件输入流写到字节数组输出流中
private byte[] readFromStream(InputStream in) {
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) != -1) {
bos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
return bos.toByteArray();
}
// 获取文件的名字
private String getFileName(String address) {
int index = address.lastIndexOf("/");
return address.substring(index + 1);
}
}