(android实战)AsycTask实现异步加载
1 实现效果说明:
1.1 加载题目信息之前,显示正在加载

1.2加载题目信息成功后,进行题目绑定

1.3加载不成功,转到加载失败

2 异步加载实现
2.1 界面设定
加载前界面
View Code
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="horizontal"
>
<ProgressBar
android:id="@+id/circleProgressBar"
style="?android:attr/progressBarStyleLarge" mce_style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:max="100"
android:progress="20"
/>
<TextView android:text="加载信息中。。。。。"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:textColor="#000000"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
加载失败界面
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="horizontal"
>
<TextView android:text="网络异常,不能加载数据" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<Button android:text="重新加载" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
2.2 创建自定义异步类
//AsyncTask
class AsyncLoader_GuessInfo extends AsyncTask<String, Void, Integer>{
@Override
protected Integer doInBackground(String... params) {
int result=0;
try{
gi=GuessDataServiceHelper.GetGuessInfo(params[0]);
result=2;
}
catch(Exception ex){
result=-1;
}
return result;
}
}
2.3 调用异步类,并根据反馈结果进行显示不同的内容
View Code
/*
* 负责做下载题目信息
* */
private BegindownHandler mbegindownHandler = new BegindownHandler();
class BegindownHandler extends Handler {
@Override
public void handleMessage(Message msg) {
AsyncTask<String,Void, Integer> results= new AsyncLoader_GuessInfo().execute(GuessNo);
try{
if( results.get()==2)
{
LoadAndBandingData(GuessNo);
}
else
setContentView(R.layout.async_error);
}
catch(Exception ex)
{
setContentView(R.layout.async_error);
}
}
public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
};

