在手机客户端与服务器交互时,如果访问的数据量过大难免会出现等待时间,这期间引入ProgressDialog或其他加载进度显示界面将会是一个很友好的选择。通常我们选择android Handler消息机制解决ProgressDialog显示的问题。但是当我们从一个Activity跳到另一个Activity之间也有很大的数据加载等待,这种情况下使用AsyncTask将会是一个很很好的选择。本文将会以Handler Message机制和AsyncTask实现android异步数据处理。
原理:
1 用户触发Button或其他数据加载事件
2 产生数据加载,发送消息,通知加载对话框
3 这期间即初始化加载对话框
4 数据记载完成,发送消息通知关闭加载对话框
1)继承Handler的MyHandler类:
[java] view plain copy
- private class MyHandle extends Handler {
- @Override
- public void handleMessage(Message msg) {
-
- super.handleMessage(msg);
- switch (msg.what) {
- case 0:
-
- Message close = new Message();
- close.what = 1;
- mHandler.sendMessage(close);
- break;
- case 1:
- if (pDialog != null) {
- pDialog.dismiss();
- }
- break;
- default:
- break;
- }
- }
- }
2)加载对话框:
[java] view plain copy
-
-
-
-
-
- private void initPDialog() {
-
- pDialog = new ProgressDialog(mContext);
- pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
- pDialog.setMessage("数据获取中。。。");
- pDialog.show();
- }
3)实例化Handler:
[java] view plain copy
-
- mHandler = new MyHandle();
4)打开加载对话框消息发送
[java] view plain copy
-
- Message open = new Message();
- open.what = 0;
- mHandler.sendMessage(open);
l AsyncTask实现
1 定义继承自AsyncTask的GetDataAsyncTask类
[java] view plain copy
- public class GetDataAsyncTask extends AsyncTask<int[], Integer, int[]> {
-
- public GetColorAsyncTask(Context context) {
- initDialog();
- }
-
-
-
-
-
-
- @Override
- protected int[] doInBackground(int[]... params) {
-
- getData();
- return data;
- }
-
-
-
-
-
-
- @Override
- protected void onCancelled() {
-
- super.onCancelled();
- }
-
-
-
-
-
-
- @Override
- protected void onPostExecute(int[] result) {
-
- super.onPostExecute(result);
-
-
-
-
- if (pDialog != null) {
- pDialog.dismiss();
- }
- }
-
-
-
-
-
-
- @Override
- protected void onPreExecute() {
-
- super.onPreExecute();
- }
-
-
-
-
-
-
- @Override
- protected void onProgressUpdate(Integer... values) {
-
- super.onProgressUpdate(values);
- }
-
- }
2) 初始化加载对话框
[java] view plain copy
-
-
-
-
-
- private void initDialog() {
-
- pDialog = new ProgressDialog(mContext);
- pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
- pDialog.setMessage("数据获取中。。。");
- pDialog.show();
- }
-
-
-
- 3)在Activity的主UI线程中实例化你的AsyncTask
[java] view plain copy
-
[java] view plain copy
-
- GetDataAsyncTask task = new GetDataAsyncTask(mContext);
- task.execute(data);
注意事项
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.)。