一、Handler及Messsage机制
1、handler用于处理消息,譬如更新UI,执行耗时任务等,主线程中执行耗时任务则需要开启新线程。Message则用来在主线程中发送消息,发送的消息会在message queen中,由looper分发给handler处理。
二、HttpURLConnection用来访问网络及文件IO流操作
1、HttpURLConnection建立起网络连接,进行基本设置,再取得流对象进行网络操作。获取方式如下
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
// InputStream in =url.openStream();
2、读取网络图片
URL url = new URL("http://192.168.1.100/yintao.jpg");// 手机访问本地服务器地址,使用本地IP地址
// 打开该URL对应的资源的输入流
InputStream is = url.openStream();
// 从InputStream中解析出图片
bitmap = BitmapFactory.decodeStream(is);
is.close();
3、读取网络文本
URL url = new URL(<a target=_blank href="http://192.168.1.100/doc.txt">http://192.168.1.100/doc.txt);</a>
InputStream is = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String string;
if ((string = reader.readLine()) != null) {
stringBuilder = stringBuilder.append(string);
}
4、存储网络数据到本地
URL url = new URL(<a target=_blank href="http://192.168.1.100/yintao.jpg">http://192.168.1.100/yintao.jpg</a>);
InputStream is = url.o