封装类 handler

public class MainActivity extends Activity {

 private Button btn;  private ImageView view;  private String path="http://www.baidu.com/img/bdlogo.gif";    @Override  protected void onCreate(Bundle savedInstanceState) {   super.onCreate(savedInstanceState);   setContentView(R.layout.activity_main);   btn=(Button) findViewById(R.id.button1);   view=(ImageView) findViewById(R.id.imageView1);   btn.setOnClickListener(new OnClickListener() {        @Override    public void onClick(View v) {     // TODO Auto-generated method stub     Down down=new Down(MainActivity.this);     down.load(path, new DownLoadContent() {            @Override      public void load(byte[] reuslt) {       // TODO Auto-generated method stub       Bitmap bitmap=BitmapFactory.decodeByteArray(reuslt, 0, reuslt.length);       view.setImageBitmap(bitmap);      }     });    }   });  }

下面的是封装类

package com.example.a;

import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog; import android.content.Context; import android.os.Handler; import android.os.Message;

public class Down {

 private ProgressDialog dialog;    public Down(Context context) {   super();   // TODO Auto-generated constructor stub   this.dialog=new ProgressDialog(context);   dialog.setMessage("load...");  }    public void load(final String path,final DownLoadContent call){      final Handler handler=new Handler(){    @Override    public void handleMessage(Message msg) {     // TODO Auto-generated method stub     super.handleMessage(msg);     byte[] result=(byte[]) msg.obj;     call.load(result);     if(msg.what==2){      dialog.dismiss();     }    }   };      class MyThread implements Runnable{

   @Override    public void run() {     // TODO Auto-generated method stub     HttpClient client=new DefaultHttpClient();     HttpPost post=new HttpPost(path);     try {      HttpResponse response=client.execute(post);      if(response.getStatusLine().getStatusCode()==200){       byte[] result=EntityUtils.toByteArray(response.getEntity());       Message message=Message.obtain();       message.obj=result;       message.what=2;       handler.sendMessage(message);      }     } catch (Exception e) {      // TODO: handle exception      e.printStackTrace();     }finally{      client.getConnectionManager().shutdown();     }    }       }   new Thread(new MyThread()).start();   dialog.show();  }      

 public interface DownLoadContent{   public void load(byte[] reuslt);  } }

 

 

posted @ 2014-03-18 00:27  萨拉克魔  阅读(231)  评论(0编辑  收藏  举报