-
在手机客户端与服务器交互时,如果访问的数据量过大难免会出现等待时间,这期间引入ProgressDialog或其他加载进度显示界面将会是一个很友好的选择。通常我们选择android Handler消息机制解决ProgressDialog显示的问题。但是当我们从一个Activity跳到另一个Activity之间也有很大的数据加载等待,这种情况下使用AsyncTask将会是一个很很好的选择。本文将会以Handler Message机制和AsyncTask实现android异步数据处理。
原理:
1 用户触发Button或其他数据加载事件
2 产生数据加载,发送消息,通知加载对话框
3 这期间即初始化加载对话框
4 数据记载完成,发送消息通知关闭加载对话框
1)继承Handler的MyHandler类:
2)加载对话框:
3)实例化Handler:
4)打开加载对话框消息发送
l AsyncTask实现
1 定义继承自AsyncTask的GetDataAsyncTask类
2) 初始化加载对话框
注意事项
l 关闭与打开对话框语句不要写在Handler提交的自定义线程内,不然会出现对话框不关闭的情形。
l 对于AsyncTask实现中,doInBackground()方法中不能访问UI和更新UI。数据的访问与加载都在这个方法中实现;如果需要访问和更新UI需要在提交Result的onPostExecute()中实现;(the doInBackground is run in the background, and while you are inthe backgroud, you CAN NOT touch the UI. AdoInBackground operation should return a result, and that result will be passedto the onPostExecute. The onPostExecute is run on the UI thread and it is herethat you can update any UI elements, which includes setting a new list adapater.)。
Handler Message 消息机制和AsyncTask异步处理android数据交互
最新推荐文章于 2021-08-24 18:58:20 发布