android AsyncTask用法

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity {

 ProgressBar pb;
 Button btn;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  pb=(ProgressBar)findViewById(R.id.progressBar1);
  pb.setVisibility(View.GONE);
  btn=(Button)findViewById(R.id.button1);
  btn.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    new DownloadAsynchTask().execute();
   }
  });

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

    private class DownloadAsynchTask extends AsyncTask<String, Integer, String>{
     @Override
     protected void onPreExecute(){
      pb.setVisibility(View.VISIBLE);
      Log.i("MainActivity", "onPreExecute");
      //Toast.makeText(getApplicationContext(), "onPreExecute", 5).show();
     }
     @Override
     protected void onProgressUpdate(Integer... values){
      pb.setProgress(values[0]);
      Log.i("MainActivity", "onProgressUpdate "+values[0]);
      //Toast.makeText(getApplicationContext(), "onProgressUpdate "+values[0], 5).show();
     }
     @Override
  protected void onPostExecute(String result) {
      pb.setVisibility(View.GONE);
      Log.i("MainActivity", "onPostExecute after "+result);
      //Toast.makeText(getApplicationContext(), "onPostExecute after "+result, 5).show();

       }

 

  @Override
  protected String doInBackground(String... params) {
   // TODO Auto-generated method stub
   Log.i("MainActivity", "doinbackground");


      for(int i=1;i<11;i++){
      try {
    Thread.sleep(1000);
    publishProgress(i);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
     }
   //Toast.makeText(getApplicationContext(), "doinbackground", 5).show();
   return "doinbackground";
  }
 }
}

 

下载时处理进度条可以如下:

       @Override
        protected String doInBackground(String... params) {

            
try{

               HttpClient client 
= new DefaultHttpClient();
               
// params[0]代表连接的url
               HttpGet get = new HttpGet(params[0]);
               HttpResponse response 
= client.execute(get);
               HttpEntity entity 
= response.getEntity();
               
long length = entity.getContentLength();
               InputStream is 
= entity.getContent();
               String s 
= null;
               
if(is != null) {
                   ByteArrayOutputStream baos 
= new ByteArrayOutputStream();

                   
byte[] buf = new byte[128];

                   
int ch = -1;

                   
int count = 0;

                   
while((ch = is.read(buf)) != -1) {

                      baos.write(buf, 
0, ch);

                      count 
+= ch;

                      
if(length > 0) {
                          
// 如果知道响应的长度,调用publishProgress()更新进度
                          publishProgress((int) ((count / (float) length) * 100));
                      }

                      
// 让线程休眠100ms
                      Thread.sleep(100);
                   }
                   s 
= new String(baos.toByteArray());              }
               
// 返回结果
               return s;
            } 
catch(Exception e) {
               e.printStackTrace();

            }

            
return null

;

        }

参考地址: http://www.cnblogs.com/dawei/archive/2011/04/18/2019903.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值