android eclipse 图片查看器 post与sendEmptyMessage更新主线程的区别

主布局文件:



    
	
	
	
	
	


主类:

public class ShowNetImageActivity extends Activity {

	private EditText imagePath_et;//声明EditText对象,即图片路径输入框
	private Button show_netimage;//声明Button对象
	private ImageView imageView;//声明ImageView对象
	private Bitmap bitmap;
	  /*post方法解决UI更新问题handler创建方式*/
//    private Handler handler_post = new Handler();
	
	 /*sendMessage方法解决UI更新问题handler创建方式*/
    Handler handler_senM = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                /*sendMessage方法更新UI的操作必须在handler的handleMessage回调中完成*/
            	imageView.setImageBitmap(bitmap);//设置显示的图片
            }
        };
    };
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image);
		/* 获取布局管理器的各个控件 */
		imagePath_et=(EditText)findViewById(R.id.imagePath_et);
		show_netimage=(Button)findViewById(R.id.show_netimage);
		imageView=(ImageView)findViewById(R.id.imageView);
		
		//为按钮点击添加事件监听器
		show_netimage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final String imagePath=imagePath_et.getText().toString();//获取图片路径
				//新建一个线程
				new Thread(new Runnable(){

					@Override
					public void run() {
						try {
							byte[] data=ImageService.getImage(imagePath);//调用ImageService类的getImage()方法,返回字节数组
							bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);//创建一个Bitmap对象
							  /*sendMessage方法解决UI更新发送消息给handler(主线程中的handler)*/
			                handler_senM.sendEmptyMessage(1);
			                
//							///*post方法解决UI更新,直接在runnable里面完成更新操作,这个任务会被添加到handler所在线程的消息队列中,即主线程的消息队列中*/
//							handler_post.post(new Runnable() {
//								@Override
//								public void run() {
//									imageView.setImageBitmap(bitmap);//设置显示的图片
//								}
//							});
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
				}).start();//开启线程
			}
		});
	}
	
}

查看上面的post方法的源码:

 /**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is 
     * attached. 
     *  
     * @param r The Runnable that will be executed.
     * 
     * @return Returns true if the Runnable was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

所以

1. post和sendMessage本质上是没有区别的,只是实际用法中有一点差别 。
2. post也没有独特的作用,post本质上还是用sendMessage实现的,post只是一中更方便的用法而已

想看例子的看客们, 点击下载

你可能感兴趣的:(移动开发)