欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

封装异步线程回调接口更新UI图片

程序员文章站 2022-06-12 19:59:12
...

封装工具类:

      1.耗时操作消息发送与接收封装到一个方法中。

      2.handler接收消息数据后,使用回调方法赋值。

 

代码如下:封装工具类

public class DownLoadContent {

	private ProgressDialog dialog;
	private static final int code = 1;
	
	public DownLoadContent(Context context){
		dialog = new ProgressDialog(context);
		dialog.setTitle("提示");
		dialog.setMessage("正在加载中");
	}
	public void download(final String path,final DownloadCallback callback){
		final Handler handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				// TODO Auto-generated method stub
				byte[] by = (byte[]) msg.obj;
				callback.loadContent(by);
				if(msg.what == code){
					dialog.dismiss();
				}
			}
		};
	    class myRunnable implements Runnable{

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(path);
				try {
					HttpResponse response = httpClient.execute(httpPost);
					if(response.getStatusLine().getStatusCode() == 200){
						byte[] result = EntityUtils.toByteArray(response.getEntity());
						Message msg = Message.obtain();
						msg.obj = result;
						msg.what = code;
						handler.sendMessage(msg);
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					httpClient.getConnectionManager().shutdown();
				}
			}
	    }
	    new Thread(new myRunnable()).start();
	    dialog.show();
	}
	//回调方法
	public interface DownloadCallback{
		
		public void loadContent(byte[] result);
	}
	
}

 

代码如下:Activity调用回调方法更新UI

public class MainActivity extends Activity {
	
	private Button button;
	private ImageView imageView;
	private final String image_path = "http://imgstatic.baidu.com/img/image/shouye/qichepaoche0822.jpg";
	
    @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.imageView1);
        button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				DownLoadContent content = new DownLoadContent(MainActivity.this);
				content.download(image_path, new DownloadCallback() {
					
					@Override
					public void loadContent(byte[] result) {
						// TODO Auto-generated method stub
						Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
						imageView.setImageBitmap(bitmap);
					}
				});
			}
		});
    }
}