AsyncTask<Params, Progress, Result>
Params:启动任务执行的输入参数类型
Progress:后台任务完成的进度值类型
Result:后台执行任务完成后返回结果的类型
使用AsyncTask只要如下三步即可:
doInBackground(Params。。。)重写该方法就是后台线程将要完成的任务,该方法可以调用publishProgress()方法更新任务的执行进度。
onProgressUpdate(Progress...)在doInBackground()方法中调用publishProgress()方法更新任务的执行进度后,将会触发该方法。
onPreExecute():该方法在执行后台耗时操作前被调用。通常该方法用于完成一些初始化的准备工作
onPostExecute(Result):当doInBackground()完成后,系统会自动调用该方法,并将doInBackground()方法的返回值传递给该方法。
public class MainActivity extends Activity {
private EditText et;
private Button bt;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
bt = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.textView1);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
DownTask task = new DownTask(MainActivity.this);
try {
task.execute(new URL("http://www.crazyit.org/ethos.php"));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
class DownTask extends AsyncTask<URL, Integer, String> {
ProgressDialog dialog;
// 定义记录已经读取的数量
int hasRead = 0;
Context mContext;
public DownTask(Context c) {
mContext = c;
}
@Override
protected void onPostExecute(String result) {
tv.setText(result);
dialog.dismiss();
}
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(mContext);
dialog.setTitle("多任务正在执行中");
dialog.setMessage("多任务正在执行请等待。。。。。。。。");
dialog.setCancelable(false);
dialog.setMax(202);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setIndeterminate(false);
dialog.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
tv.setText("已经读取了" + values[0] + "行");
dialog.setProgress(values[0]);
}
@Override
protected String doInBackground(URL... arg0) {
StringBuilder sb = new StringBuilder();
try {
URLConnection conn = arg0[0].openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
hasRead++;
publishProgress(hasRead);
}
return sb.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
原文地址:http://blog.csdn.net/aimingkun/article/details/45024677