Handler和Message(一)

大家都知道不能在主线程实现下载 更新等耗时的操作,今天就通过Handler和Message实现

  直接附上操作代码:

package com.example.android_01;


import java.io.IOException;
import java.io.InputStream;


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


import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Switch;


public class MainActivity extends Activity implements OnClickListener {
private Button but;
private ImageView img;
private ProgressDialog dialog;
private final int IS_FINISH = 1;
private String imgPath = "http://b.hiphotos.baidu.com/image/pic/item/b3b7d0a20cf431adca2819384936acaf2edd983c.jpg";//下载图片的链接
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
byte b[]=(byte[]) msg.obj;
Bitmap bm=BitmapFactory.decodeByteArray(b, 0, b.length);//通过BitmapFactory把byte转化成bitmap
img.setImageBitmap(bm);
if(msg.arg1==IS_FINISH){
dialog.dismiss();
}


}
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.but = (Button) this.findViewById(R.id.button1);
this.img = (ImageView) this.findViewById(R.id.imageView1);
this.dialog = new ProgressDialog(this);
this.dialog.setTitle("提示");
this.dialog.setMessage("下载中~~");


this.but.setOnClickListener(this);
}


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
this.dialog.show();
new Thread(new MyThread()).start();
}


}


public class MyThread implements Runnable {


@Override
public void run() {
//实现下载操作
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(imgPath);
InputStream input = null;
try {
HttpResponse httpres = httpclient.execute(httpget);
if (httpres.getStatusLine().getStatusCode() == 200) {
byte b[] = EntityUtils.toByteArray(httpres.getEntity());
Message msg = Message.obtain();
msg.obj = b;
msg.arg1 = IS_FINISH;
handler.sendMessage(msg);


}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


}


}

 

 

你可能感兴趣的:(Handler和Message(一))