Android核心技术之(5)---消息机制与异步任务

来源:互联网 发布:mac os x 5k原生壁纸 编辑:程序博客网 时间:2024/04/29 22:11

1.理论概述

•在Android中,只有在UIThread才能直接更新界面

•在Android中,长时间的工作(联网)都需要在workerThread中执行

•在分线程获得服务器数据后, 需要立即到主线程中去更新界面显示数据

•如何实现线程间通信呢?消息机制&异步任务

2.消息机制的相关API

•Message :消息  
•可理解为线程间通讯的数据单元, 可通过message携带需要的数据
•创建对象:  Message.obtain(what)
•封装数据

  public int what    //id 标识

  public int arg1

  public int arg2

  public Object obj

•Handler : 处理器
•Handler是Message的处理器,同时也负责消息的发送和移除的工作
•发送即时消息:  sendMessage(Message msg)
•发送延时消息:  sendMessageDelayed(Message msg, long time)
•处理消息: handleMessage(Message msg)   (回调方法)
•移除还未处理的消息: removeMessages(int what)

•MessageQueue : 消息队列
•用来存放通过Handler发送的消息
•它是一个按Message的when排序的优先级队列
•Looper(钩子) : 循环器
•负责循环取出Message Queue里面的当前需要处理的Message
•交给对应的Handler进行处理
•处理完后, 将Message缓存到消息池中, 以备复用

3.理论概述

•什么是异步任务?
逻辑上:以多线程的方式完成的功能需求
•API上:指AsyncTask类

•AsyncTask的理解
•在没有AsyncTask之前, 我们用Handler+Thread就可以实现异步任务的功能需求
•AsyncTask是对Handler和Thread的封装,使用它编码更简洁,更高效
•AsyncTask封装了ThreadPool, 比直接使用Thread效率要高

4.AsyncTask相关API

•AsyncTask: 简化Handler处理多线程通信的问题
•AsyncTask<Params, Progress, Result>
•Params  启动任务执行的输入参数,比如HTTP请求的URL。
•Progress 后台任务执行的百分比。
•Result 后台执行任务最终返回的结果,比如String。
•execute(Params... params) 启动任务, 开始任务的执行流程
•void onPreExecute() 在分线程工作开始之前在UIThread中执行,一般用来显示提示视图
•Result doInBackground(Params... params) 在workerThread中执行,完成任务的主要工作,通常需要较长的时间
•void onPostExecute(Result result)   在doInBackground()执行完后在UIThread中执行,一般用来更新界面
•publish Progress(Progress... values) : 在分线程中, 发布当前进度
•void onProgressUpdate(Progress... values) : 在主线程中更新进度


5.json转换

package com.atguigu.l05_handler;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.test.AndroidTestCase;
import android.util.Log;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


/*
1. 将json格式的字符串{}转换为Java对象, 使用原生API
2. 将json格式的字符串{}转换为Java对象, 使用GSON
3. 将json格式的字符串[]转换为Java对象的List, 使用原生API
4. 将json格式的字符串[]转换为Java对象的List, 使用GSON


5. 将Java对象转换为json字符串{}, 使用GSON
6. 将Java对象的List转换为json字符串[], 使用GSON
 */
public class JsonTest extends AndroidTestCase{


/*
* 1. 将json格式的字符串{}转换为Java对象, 使用原生API
*/
public void testJsonToObject() throws JSONException {
String jsonString = "{\"id\":2, \"name\":\"大虾\", \"price\":12.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"}";

//将json字符串封装为JSONObject对象
JSONObject jsonObject = new JSONObject(jsonString);
//从对象中根据key得到对应的value
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
double price = jsonObject.getDouble("price");
String imagePath = jsonObject.getString("imagePath");
//封装ShopInfo对象
ShopInfo shopInfo = new ShopInfo(id, name, price, imagePath);

Log.e("TAG", shopInfo.toString());
}

/*
* 1. 将json格式的字符串{}转换为Java对象, 使用GSON
*/
public void testJsonToObject2()  {
String jsonString = "{\"id\":3, \"name\":\"大虾\", \"price\":12.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"}";

ShopInfo shopInfo = new Gson().fromJson(jsonString, ShopInfo.class);

Log.e("TAG", shopInfo.toString());
}


/*
* 3. 将json格式的字符串[]转换为Java对象的List, 使用原生API
*/
public void testJsonToList() throws JSONException {
String jsonString = "[{\"id\":3, \"name\":\"大虾\", \"price\":12.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"},"
+ "{\"id\":5, \"name\":\"大虾2\", \"price\":128.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f2.jpg\"}]";
List<ShopInfo> list = new ArrayList<ShopInfo>();

//1. 将json字符串包装JSONArray对象
JSONArray jsonArray = new JSONArray(jsonString);
//2. 遍历JSONArray对象所有元素(JSONObject), 并将每个元素封装为shopInfo, 并添加到List
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//从对象中根据key得到对应的value
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
double price = jsonObject.getDouble("price");
String imagePath = jsonObject.getString("imagePath");
//封装ShopInfo对象
ShopInfo shopInfo = new ShopInfo(id, name, price, imagePath);
list.add(shopInfo);
}

Log.e("TAG", list.toString());
}

/*
* 4. 将json格式的字符串[]转换为Java对象的List, 使用GSON
*/
public void testJsonToList2() throws JSONException {
String jsonString = "[{\"id\":4, \"name\":\"大虾\", \"price\":12.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"},"
+ "{\"id\":6, \"name\":\"大虾2\", \"price\":128.3,\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f2.jpg\"}]";

List<ShopInfo> list = new Gson().fromJson(jsonString, new TypeToken<List<ShopInfo>>(){}.getType());

Log.e("TAG", list.toString());
}

/*
5. 将Java对象转换为json字符串{}, 使用GSON
*/
public void testObjectToJson() {
ShopInfo info = new ShopInfo(3, "KK", 1000, "http://www.sina.com");
String json = new Gson().toJson(info);
Log.e("TAG", json);
}


/*
6. 将Java对象的List转换为json字符串[], 使用GSON
*/

public void testListToJson() {

List<ShopInfo> list = new ArrayList<ShopInfo>();
list.add(new ShopInfo(3, "KK", 1000, "http://www.sina.com"));
list.add(new ShopInfo(4, "KK2", 2000, "http://www.sina.com222"));

String json = new Gson().toJson(list);

Log.e("TAG", json);
}

public void testJsonToMap() {
String jsonString = "{\"my name\":\"大虾\", \"1\":12}";
Map<String, Object> map = new Gson().fromJson(jsonString, new TypeToken<Map<String, Object>>(){}.getType());
Log.e("TAG", map.toString());
}
}



0 0