异步加载数据的三种实现(二)

2014-11-24 09:44:18 · 作者: · 浏览: 6
essDialog = new ProgressDialog(context);
progressDialog.setTitle("进度条");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

textView1 = (TextView) findViewById(R.id.textView1);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(l);

}

private OnClickListener l = new OnClickListener() {

@Override
public void onClick(View v) {
new InitTask().execute("http://wap.sina.com",
"http://wap.baidu.com");

}
};

private void getHtmlDate(String url) {// 获取数据,把线程写入了其中

try {
html = HttpUtil.fromHtml(HttpUtil.getHtml(url));
} catch (Exception e) {
e.printStackTrace();
}

}

/**
* When an asynchronous task is executed, the task goes through 4 steps:
*
* onPreExecute(),
* invoked on the UI thread immediately after the task is
* executed. This step is normally used to setup the task, for instance by
* showing a progress bar in the user interface.
*
* doInBackground(Params...),
* invoked on the background thread immediately after onPreExecute()
* finishes executing. This step is used to perform background computation
* that can take a long time. The parameters of the asynchronous task are
* passed to this step. The result of the computation must be returned by
* this step and will be passed back to the last step. This step can also
* use
*
* publishProgress(Progress...) to publish one or more units of
* progress. These values are published on the UI thread, in the
*
* onProgressUpdate(Progress...) step. onProgressUpdate(Progress...),
* invoked on the UI thread after a call to publishProgress(Progress...).
* The timing of the execution is undefined. This method is used to display
* any form of progress in the user interface while the background
* computation is still executing. For instance, it can be used to animate a
* progress bar or show logs in a text field. onPostExecute(Result), invoked
* on the UI thread after the background computation finishes. The result of
* the background computation is passed to this step as a parameter.
*/

class InitTask extends AsyncTask {
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();

}

protected Long doInBackground(String... params) {// Long是结果 String 是入口参数

getHtmlDate(params[0]);// 可以运行两个任务
publishProgress(50);// 发送进度50%
getHtmlDate(params[1]);
publishProgress(100);// 发送进度100%

return (long) 1;

}

@Override
protected void onProgressUpdate(Integer... progress) {

progressDialog.setProgress(progress[0]);// 设置进度
super.onProgressUpdate(progress);
Log.e("测试", progress[0] + "");

}

@Override
protected void onPostExecute(Long result) {

setTitle(result + "测试");
textView1.setText(html);
progressDialog.dismiss();

super.onPostExecute(result);

}

}

}

[java]
package com.testasyntextview;
/**
* 使用Runable
*/
import android.app.Activity;
import android.app.ProgressDialog;
import and