http://blog.youkuaiyun.com/crystal923129/article/details/6739575
方法一:使用android提供的方法
举例: 在work thread中更新UI mImageView,调用mImageView的post方法,这个方法将在main线程中执行- public void onClick(View v) {
- new Thread(new Runnable() {
- public void run() {
- final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");
- mImageView.post(new Runnable(){
- public void run() {
- mImageView.setImageBitmap(bitmap);
- }
- });
- }
- }).start();
- }
方法二:使用AsyncTask
需要实现的方法:
doInBackground() :运行在后台线程池中
onPostExecute() : 运行在main线程中,传递 doInBackground()执行的结果
onPreExecute() : 运行在main线程中
onProgressUpdate(): 运行在main线程中
其它protected方法:
publishProgress() : 可以在 doInBackground()中随时调用,用于触发onProgressUpdate()的执行
公共方法:
execute():执行该task
cancle() :随时取消该task,可以在任何线程中调用
举例:
- public void onClick(View v) {
- new DownloadImageTask().execute("http://example.com/image.png");
- }
- private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
- protected Bitmap doInBackground(String... urls) {
- return loadImageFromNetwork(urls[0]);
- }
- protected void onPostExecute(Bitmap result) {
- mImageView.setImageBitmap(result);
- }
- }
方法三:使用Handler 和Thread实现
Thread中需要更新UI的部分,向main thread中的handler发送消息sendMessage/postMessage,传递更新所需要的参数,handler重写handleMessage方法处理消息 ,更新UI
举例:
- Handler myHandler = new Handler() {
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case TestHandler.GUIUPDATEIDENTIFIER: mImageView.invalidate();
- break;
- }
- super.handleMessage(msg);
- }
- };
- class myThread implements Runnable {
- public void run() {
- while(!Thread.currentThread().isInterrupted()) {
- Message message = new Message();
- message.what = TestHandler.GUIUPDATEIDENTIFIER;
- TestHandler.this.myHandler.sendMessage(message);
- try {Thread.sleep(100); }
- catch(InterruptedException e)
- { Thread.currentThread().interrupt(); }
- }
- }