您的位置:首页 > 理论基础 > 计算机网络

使用Handler更新图片,结合了HttpCliet 和ProgressDialog

2015-07-28 17:56 591 查看
首先是java文件代码

public class MainActivity extends Activity {

private String image_path = "https://www.baidu.com/img/bdlogo.png";
private Button button;
private ImageView imageView;
private ProgressDialog dialog;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {

byte[] bit = (byte[]) msg.obj;
Bitmap bitmap = BitmapFactory.decodeByteArray(bit, 0, bit.length); // 把数据设置为bitmpa
imageView.setImageBitmap(bitmap);
if (msg.what == 1) {
dialog.dismiss();// 隐藏progressDialog
}
};
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button = (Button) findViewById(R.id.button1);
imageView = (ImageView) findViewById(R.id.image);
dialog = new ProgressDialog(this);
dialog.setTitle("下载任务");
dialog.setMessage("loading......");
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
new Thread(new MyRunnable()).start();// 开启线程去执行下载任务
dialog.show();// 显示progresDialog
}
});
}

class MyRunnable implements Runnable {

@Override
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(image_path);
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
byte[] resule = EntityUtils.toByteArray(response
.getEntity());
Message message = Message.obtain();
message.obj = resule;
message.what = 1;
handler.sendMessage(message);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();// 最后要关闭
}
}

}
}


然后是xml中的布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
android:id="@+id/image"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:src="@drawable/ic_launcher" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/image"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp"
android:text="下载图片" />

</RelativeLayout>


最后记得要在注册文件中,写上Intenet的权限,效果如下



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: