Android 实现在线程中联网

其实我们要牢记的是,对数据流的操作都是阻塞的,在一般情况下,我们是不需要考虑这个问题的,但是在 Android  实现联网的时候,我们必须考虑到这个问题。比如:从网络上下载一张图片:

Java代码:
  1. public Bitmap returnBitmap(String url)
  2. {
  3. URL myFileUrl = null;
  4. Bitmap bitmap = null;
  5. try{
  6. myFileUrl = new URL(url);
  7. }catch(MalformedURLException e){
  8. e.printStackTrace();
  9. return null;
  10. };
  11. try{
  12. HttpURLConnection conn = (HttpURLConnection)myFileUrl.openConnection();
  13. conn.setDoInput(true);
  14. conn.connect();
  15. InputStream is = conn.getInputStream();
  16. bitmap = BitmapFactroy.decodeStream(is);
  17. is.close();
  18. }catch(IOException e){
  19. e.printStackTrace();
  20. }
  21. return bitmap;
  22. }
复制代码

                 由于网络连接需要很长的时间,需要3-5秒,甚至更长的时间才能返回页面的内容。如果此连接动作直接在主线程,也就是UI线程中处理,会发生什么情况呢? 整个程序处于等待状态,界面似乎是“死”掉了。为了解决这个问题,必须把这个任务放置到单独线程中运行,避免阻塞 UI线程 ,这样就不会对主线程有任何影 响。举个例子如下:

Java代码:
  1. private void connect(String strURL){
  2. new Thread() {
  3. public void run() {
  4. try {
  5. HttpClient client = new DefaultHttpClient();
  6. // params[0]代表连接的url
  7. HttpGet get = new HttpGet(url.getText().toString());
  8. HttpResponse response = client.execute(get);
  9. HttpEntity entity = response.getEntity();
  10. long length = entity.getContentLength();
  11. InputStream is = entity.getContent();
  12. String s = null;
  13. if (is != null) {
  14. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  15. byte[] buf = new byte[128];
  16. int ch = -1;
  17. int count = 0;
  18. while ((ch = is.read(buf)) != -1) {
  19. baos.write(buf, 0, ch);
  20. count += ch;
  21. }
  22. s = new String(baos.toByteArray());
  23. Log.V(“moandroid sample”,s);
  24. }
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }.start();
  30. }
复制代码

                 使用Handler更新界面

                 如何将下载的信息显示在界面上了,比如说下载的进度。 Android SDK 平台只允许在主线程中调用相关 View 的方法来更新界面。如果返回结果在新线程中获得,那么必须借助 Handler 来更新界面。为此,在界面  Activity 中创建一个 Handler 对象,并在 handleMessage() 中更新 UI

Java代码:
  1. //Task在另外的线程执行,不能直接在Task中更新UI,因此创建了Handler
  2. private Handler handler = new Handler() {
  3. @Override
  4. public void handleMessage(Message msg) {
  5. String m = (String) msg.obj;
  6. message.setText(m);
  7. }
  8. }; 

  9. //只需要将上面的
  10. Log.V(“moandroid sample”,s); 

  11. //替换为:
  12. s = new String(baos.toByteArray());
  13. Message mg = Message.obtain();
  14. mg.obj = s;
  15. handler.sendMessage(mg);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值