热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Handler和Message(一)

1.Activity代码importorg.apache.http.HttpResponse;importorg.apache.http.client.HttpClient;
1. Activity代码

import org.apache.http.HttpResponse;
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.View;
import android.widget.Button;
import android.widget.ImageView;public class HandlerActivity extends Activity {private Button button = null;private ImageView imageView = null;private String image_path = "http://11.203.18.14:8080/image/001.png";private ProgressDialog dialog = null;private static final int IS_FINISH = 1;private Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubbyte[] data = (byte[])msg.obj;Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);imageView.setImageBitmap(bm);if(msg.what == IS_FINISH){dialog.dismiss();}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);button = (Button)findViewById(R.id.button1);imageView = (ImageView)findViewById(R.id.imageView1);dialog = new ProgressDialog(HandlerActivity.this);dialog.setTitle("提示");dialog.setMessage("正在下载,请稍后......");dialog.setCancelable(false);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubnew Thread(new MyThread()).start();}});}//重新定义一个线程public class MyThread implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubHttpClient httpClient = new DefaultHttpClient();HttpGet httpGet = new HttpGet(image_path);HttpResponse httpResponse = null;
// InputStream inputStream = null;try{httpResponse = httpClient.execute(httpGet);if(httpResponse.getStatusLine().getStatusCode()==200){byte[] data = EntityUtils.toByteArray(httpResponse.getEntity());Message message = Message.obtain();message.obj = data;message.what = IS_FINISH;handler.sendMessage(message);}}catch(Exception e){e.printStackTrace();}}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.handler, menu);return true;}}

2. main.xml文件



3. 注册文件添加网络连接







推荐阅读
author-avatar
1076263105_69ae53
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有