Android AsyncTask
private Button btn; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView) findViewById(R.id.tv); findViewById(R.id.btn).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ReadURl("http://www.baidu.com"); } }); } public void ReadURl(String url){ //初始化数据是传入的数据类型、处理过程中返回值的数据类型、处理完成后返回值的数据类型 new AsyncTask<String, Float, String>() { //执行后台耗时操作 @Override protected String doInBackground(String... params) { try { URL url=new URL(params[0]); URLConnection connection=url.openConnection(); long total=connection.getContentLength(); InputStream Istream=connection.getInputStream(); InputStreamReader isr=new InputStreamReader(Istream); BufferedReader br=new BufferedReader(isr); String line; StringBuilder builder=new StringBuilder(); while ((line=br.readLine())!=null) { builder.append(line); publishProgress((float)builder.toString().length()/(float)total); //调用publishProgress对外发布当前进度 } br.close(); Istream.close(); return builder.toString(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onCancelled() { // TODO Auto-generated method stub super.onCancelled(); } @Override protected void onCancelled(String result) { // TODO Auto-generated method stub super.onCancelled(result); } @Override protected void onPostExecute(String result) { tv.setText(result); super.onPostExecute(result); } //在AsyncTask执行之前执行 @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); } //在AsyncTask执行的过程中,对外发布当前执行的进度 @Override protected void onProgressUpdate(Float... values) { Toast.makeText(MainActivity.this, values[0]+"",Toast.LENGTH_SHORT).show(); super.onProgressUpdate(values); } }.execute(url); }
可以参考:
http://www.cnblogs.com/devinzhang/archive/2012/02/13/2350070.html
http://blog.csdn.net/liuhe688/article/details/6532519
stareblankly.cn