AsyncTask实例

来源:互联网 发布:虚拟机 linux nat 编辑:程序博客网 时间:2024/06/03 22:49

public class MainActivity extends Activity {
private TextView show;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
show= (TextView) findViewById(R.id.show);

}public void download(View source) throws MalformedURLException{    DownTask task=new DownTask(this);    task.execute(new URL("http://www.crazyit.org/ethos.php"));}class DownTask extends AsyncTask<URL,Integer,String>{    ProgressDialog pdialog;    int hasRead=0;    Context mContext;    public DownTask(Context ctx) {        mContext = ctx;    }

//子线程,执行耗时操作
@Override
protected String doInBackground(URL… params) {
StringBuilder sb = new StringBuilder();
try {
URLConnection conn=params[0].openConnection();
BufferedReader br= new BufferedReader(new InputStreamReader(conn.getInputStream(),”utf-8”));
String line=null;
while ((line=br.readLine())!=null){//br.readline:下一行
sb.append(line+”\n”);
hasRead++;
publishProgress(hasRead);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

    @Override    protected void onPostExecute(String result) {        show.setText(result);        pdialog.dismiss();    }

//主线程
@Override
protected void onPreExecute() {
pdialog=new ProgressDialog(mContext);
pdialog.setTitle(“任务正在执行中”);
pdialog.setMessage(“敬请等待…”);
pdialog.setCancelable(false);
pdialog.setMax(202);
pdialog.setIndeterminate(false);
pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pdialog.show();
}
//主线程
@Override
protected void onProgressUpdate(Integer… values) {
show.setText(“已经读取了[“+values[0]+”]行!”);
pdialog.setProgress(values[0]);
}
}
}

1 0
原创粉丝点击