使用Handler更新图片,结合了HttpCliet 和ProgressDialog
2015-07-28 17:56
591 查看
首先是java文件代码
然后是xml中的布局文件
最后记得要在注册文件中,写上Intenet的权限,效果如下
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的权限,效果如下
相关文章推荐
- C# HttpWebRequest post提交数据,提交对象
- HTTP Error 500.23
- pthread编程基础 http://blog.chinaunix.net/uid-20528014-id-333508.html
- http 协议详解
- qperf测量网络带宽和延迟
- iOS面试题--网络--如何处理多个网络请求的并发的情况
- AppStore 发布游戏分辨率列表。 From:https://itunesconnect.apple.com
- iOS开发遇到的坑之三--使用asi框架在xcode下正常运行,但是打包时却不能进行网络访问
- 计算机网络(二)
- 如何去选择CDN网络加速?深圳锐网科技
- 回顾:中网通讯网络公司CEO罗与曾作客新浪嘉宾聊天室
- Volley的Https请求
- java https连接
- poj1637 混合图欧拉回路的求解 网络流
- 配置Tomcat使用https协议(配置SSL协议)
- Apache利用JDK自身keytool实现HTTPS
- CentOS 6.6 新安装系统的网络IP配置
- Apache 映射端口-http_proxy方式
- samba服务器的安装及网络共享
- 网络访问,返回状态码