android提供了一套专门用于异步处理的类。即:AynsTask类。使用这个类可以为耗时程序开辟一个新线程进行处理,处理完时返回。

AsyncTask的回调逻辑关系

 1.主线程调用AsynTask子类实例的execute()方法后,首先会调用onPreExecute()方法。onPreExecute()在主线程中运行,可以用来写一些开始提示代码。

 2.之后启动新线程,调用doInBackground()方法,进行异步数据处理。如果在doInBackground()方法异步处理的时候,如果希望通知主线程一些数据(如:处理进度)。这时,可以调用publishProgress()方法。这时,主线程会调用AsynTask子类的onProgressUpdate()方法进行处理。

 3.处理完毕之后异步线程结束,在主线程中调用onPostExecute()方法。onPostExecute()可以进行一些结束提示处理。

下面是一个实例:另开一个线程解析从网络上得到的数据(国家气象局的北京实时天气)

例子的目录结构:


com.asynctask.handler包:

/*===============异步操作类中方法的执行顺序===============*///1.生成该类的对象,调条用其execute()方法之后首先执行的是onPreExecute()方法//2.其次执行 doInBackground(Params...)方法。如果在该方法中每次调用publishProgress(Progress...)方法,都会触发onProgressUpdata(Progress...)方法。//3.最后执行onPostExecute(Result)方法。public class MyAsyncTask extendsAsyncTask<String, Integer, List<Map<String, String>>> {private TextView cityname = null;private TextView cityid = null;private TextView temp = null;private TextView weather = null;private TextView ptime = null;public MyAsyncTask(Context context, TextView cityname, TextView cityid,TextView temp, TextView weather, TextView ptime) {this.cityname = cityname;this.cityid = cityid;this.temp = temp;this.weather = weather;this.ptime = ptime;}// 此函数在另外一个线程中运行,不能操作UI线程中的控件protected List<Map<String, String>> doInBackground(String... params) {String path = "http://www.weather.com.cn/data/cityinfo/101010100.html";URL url = null;HttpURLConnection httpConnection = null;List<Map<String, String>> list = new ArrayList<Map<String, String>>();HashMap<String, String> map = null;//System.out.println("异步操作开始");try {url = new URL(path);httpConnection = (HttpURLConnection) url.openConnection();if (httpConnection.getResponseCode() == 200) {//System.out.println("网络已连接");// 流转换成为字符串InputStream inputStream = httpConnection.getInputStream();String strResult = "";byte[] b = new byte[1024];int i = 0;while ((i = inputStream.read(b)) != -1) {strResult += new String(b);b = new byte[1024];}// 开始解析JSON字符串JSONObject jsonObject = new JSONObject(strResult);JSONObject jsonObject1 = jsonObject.getJSONObject("weatherinfo");map = new HashMap<String, String>();String city = jsonObject1.getString("city");String cityid = jsonObject1.getString("cityid");String temp1 = jsonObject1.getString("temp1");String temp2 = jsonObject1.getString("temp2");String weather = jsonObject1.getString("weather");String img1 = jsonObject1.getString("img1");String img2 = jsonObject1.getString("img2");String ptime = jsonObject1.getString("ptime");map.put("city", city);map.put("cityid", cityid);map.put("temp1", temp1);map.put("temp2", temp2);map.put("weather", weather);map.put("img1", img1);map.put("img2", img2);map.put("ptime", ptime);list.add(map);/*// 测试System.out.println(city);System.out.println(cityid);System.out.println(temp1);System.out.println(temp2);System.out.println(weather);System.out.println(img1);System.out.println(img2);System.out.println(ptime);*/} } catch (Exception e) {e.printStackTrace();}return list;}// 在doInBackground()方法执行结束之后才开始运行,并且运行在UI线程中,可以对UI线程中的控件进行操作protected void onPostExecute(List<Map<String, String>> list) {HashMap<String, String> map = new HashMap<String, String>();map = (HashMap<String, String>) list.get(0);// String city = map.get("city");// System.out.println(city);cityname.setText(map.get("city"));cityid.setText(map.get("cityid"));temp.setText(map.get("temp1") + "~" + map.get("temp2"));weather.setText(map.get("weather"));ptime.setText(map.get("ptime"));}}

com.asynctask.activity包:

public class MainActivity extends Activity {    private TextView cityname;private TextView cityid;private TextView temp;private TextView weather;private TextView ptime;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                cityname = (TextView) findViewById(R.id.cityname);cityid = (TextView) findViewById(R.id.cityid);temp = (TextView) findViewById(R.id.temp);weather = (TextView) findViewById(R.id.weather);ptime = (TextView) findViewById(R.id.ptime);                MyAsyncTask mAsyncTask = new MyAsyncTask(this,cityname,cityid,temp,weather,ptime);        mAsyncTask.execute();    }}

运行效果图:




更多相关文章

  1. Activity生命机制与状态保存机制
  2. android 应用开发框架
  3. Android中为TextView增加自定义的HTML标签
  4. 编写高效的android代码(译文)
  5. [置顶] 【Android应用开发】Android(安卓)Studio - MAC 版 - 快
  6. Android下打印调试堆栈方法
  7. android倒计时的简单实现
  8. 【Android】用AsyncTask实现多线程
  9. Android(安卓)RxJava系列一: 基础常用详解

随机推荐

  1. ScrollView不能包含多个子项,ScrollView c
  2. 世界范围内浏览器市场份额调查,symbian不
  3. Android(安卓)3.0 访问WebService 出现 a
  4. 自定义ActionBar标题与菜单中的文字样式
  5. reactNative 集成支付宝支付
  6. Android判断定位功能是否可用
  7. Android fragment 与Activity 互相传值。
  8. Android开发高级进阶02
  9. Android之获取手机相关信息
  10. Android Studio导入Android平台源码