android系统中的多线程(二): 关于在work thread中对UI进行更新和设置

来源:互联网 发布:sql 重复数据 编辑:程序博客网 时间:2024/05/29 16:04

http://blog.csdn.net/crystal923129/article/details/6739575


方法一:使用android提供的方法

  • Activity.runOnUiThread(Runnable)
  • View.post(Runnable)
  • View.postDelayed(Runnable, long)
举例: 在work thread中更新UI mImageView,调用mImageView的post方法,这个方法将在main线程中执行
[java] view plaincopy
  1. public void onClick(View v) {  
  2.     new Thread(new Runnable() {  
  3.         public void run() {  
  4.             final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");  
  5.             mImageView.post(new Runnable(){  
  6.                 public void run() {  
  7.                    mImageView.setImageBitmap(bitmap);  
  8.                 }  
  9.             });  
  10.         }  
  11.     }).start();  
  12. }  

方法二:使用AsyncTask
需要实现的方法

 doInBackground() :运行在后台线程池中
 onPostExecute()  : 运行在main线程中,传递 doInBackground()执行的结果
 onPreExecute()    : 运行在main线程中
 onProgressUpdate(): 运行在main线程中
其它protected方法:
 publishProgress()  : 可以在 doInBackground()中随时调用,用于触发onProgressUpdate()的执行
公共方法:
execute():执行该task
cancle() :随时取消该task,可以在任何线程中调用

 

举例:
[java] view plaincopy
  1. public void onClick(View v) {  
  2.     new DownloadImageTask().execute("http://example.com/image.png");  
  3. }  
  4. private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {  
  5.      
  6. protected Bitmap doInBackground(String... urls) {  
  7.         return loadImageFromNetwork(urls[0]);  
  8.     }  
  9.      
  10.     protected void onPostExecute(Bitmap result) {  
  11.         mImageView.setImageBitmap(result);  
  12.     }  
  13. }  

方法三:使用Handler 和Thread实现
Thread中需要更新UI的部分,向main thread中的handler发送消息sendMessage/postMessage,传递更新所需要的参数,handler重写handleMessage方法处理消息 ,更新UI
举例:
[java] view plaincopy
  1. Handler myHandler = new Handler() {  
  2.   public void handleMessage(Message msg) {  
  3.     switch (msg.what) {  
  4.        case TestHandler.GUIUPDATEIDENTIFIER: mImageView.invalidate();  
  5.               break;  
  6.     }  
  7.     super.handleMessage(msg);  
  8.   }  
  9. };  
  10.    
  11. class myThread implements Runnable {  
  12.  public void run() {  
  13.   while(!Thread.currentThread().isInterrupted()) {  
  14.    Message message = new Message();  
  15.    message.what = TestHandler.GUIUPDATEIDENTIFIER;         
  16.    TestHandler.this.myHandler.sendMessage(message);  
  17.    try {Thread.sleep(100); }  
  18.    catch(InterruptedException e)  
  19.    { Thread.currentThread().interrupt(); }  
  20.   }  
  21.  }   

原创粉丝点击