Android学习笔记【04】【网络编程之一】

阶段1  数据存储与界面展示

阶段2  网络编程

阶段3  四大组件

阶段4  多媒体

阶段5  新特性

一、网页源码查看器

抓包工具:HttpWatchPro

安装后在浏览器中打开快捷键:shift+F2

 1 String path = et_path.getText().toString().trim();
 2 
 3 URL url = new URL(path);
 4 Log.d("data", path);
 5 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 6 
 7 //设置请求类型
 8 conn.setRequestMethod("GET");//默认GET请求
 9 //设置超时时间
10 conn.setConnectTimeout(5000);
11 //获取返回状态码
12 int code = conn.getResponseCode();
13 if (code == 200) {
14     //获取返回数据
15     InputStream in = conn.getInputStream();
16 
17     String content = StreamTools.readStream(in);
18     Log.d("data", content);
19     tv_result.setText(content);
20 }

HttpURLConnection:用于发送和接收数据

ScrollView只能有一个子节点

二、消息机制的写法

ANR=Application NOT Response

如果主线程中进行耗时操作(如连接网络、复制大量数据)会异常

耗时操作均放到子线程中

4.0之后,谷歌强制要求不能在主线程连接网络(NetworkOnMainThreadException)

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

只有主线程才可以更新UI

消息机制

三、handler原理

使用步骤:

1、主线程定义一个Handler

2、重写handleMessage方法

1 private Handler handler = new Handler() {
2         @Override
3         public void handleMessage(Message msg) {
4 
5             tv_result.setText(msg.obj.toString());
6         }
7 };

3、子线程发消息给主线程handleMessage执行处理

1 Message msg = new Message();
2 msg.obj = content;
3 //发送消息后,handleMessage会执行
4 handler.sendMessage(msg);

handler作用:发消息和处理消息

Looper作用:去消息队列中取消息

四、图片查看器

 返回流转换成Bitmap:

使用BitmapFactory类可以将各种类型转换成Bitmap对象

五、runOnUiThread写法

runOnUiThread(Runnable() action):action在主线程运行

1 runOnUiThread(new Runnable() {
2                             @Override
3                             public void run() {
4                                 iv.setImageBitmap(bitmap);
5                             }
6 });

六、常见消息API

1 //Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses.
2 final boolean postDelayed(Runnable r, long delayMillis);

七、新闻客户端

需求分析:

八、开源项目SmartImageView介绍

1、把com包拷贝到当前工程

2、使用SmartImageView的时候,布局文件定义控件需要包的完整路径加类名

九、SmartImageView原理

原文地址:https://www.cnblogs.com/leishoulin/p/7420705.html