本实例只有一个按钮和文本框,点击按钮从网络下载数据,然后又在文本框显示。
package peng.liu.test;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends Activity{
private TextView tvAsync;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvAsync = (TextView) findViewById(R.id.tvAsync);
}
public void download(View source) throws MalformedURLException {
DownTask downTask = new DownTask(this);
downTask.execute(new URL("http://www.carzyit.org/ethos.php"));
}
class DownTask extends AsyncTask<URL,Integer,String>{
ProgressDialog dialog;
int hasdata;
Context context;
public DownTask(Context ctx){
this.context = ctx;
}
@Override
protected String doInBackground(URL... urls) {
StringBuilder sb = new StringBuilder();
try {
URLConnection conn = urls[0].openConnection();
BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String line = null;
while ((line = bf.readLine()) != null){
sb.append(line);
hasdata++;
publishProgress(hasdata);
}
return sb.toString();
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
tvAsync.setText(s);
dialog.dismiss();
}
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setTitle("hello");
dialog.setCancelable(false);
dialog.setMessage("world");
dialog.setMax(202);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setIndeterminate(false);
dialog.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
tvAsync.setText(hasdata+"");
dialog.setProgress(values[0]);
}
}
}
AsyncTask(异步任务)讲解-android的学习之旅(四十六)
原文地址:http://blog.csdn.net/lpjishu/article/details/46592235