使用Handler在子線程中更新UI


       Android規定僅僅能在主線程中更新UI。假設在子線程中更新UI 的話會提演示樣例如以下錯誤:Only the original thread that created a view hierachy can touch its view((僅僅有原來的線程創建一個視圖層次能夠觸摸它的視圖)。

      僅僅能在主線程中更新UI的原因是:android中相關的view和控件不是線程安全的,我們必須單獨做處理。

      有的時候須要再子線程中實現更新UI,以下介紹使用Handler實現線程通信的特點實如今子線程中更新UI。

Handler的使用場合:

1、 to schedule messages and runnables to be executed as some point in the future;

      安排messages和runnables在將來的某個時間點運行。

2、 to enqueue an action to be performed on a different thread than your own.

      將action入隊以備在一個不同的線程中運行。即能夠實現線程間通信。比方當你創建子線程時。你能夠再你的子線程中拿到父線程中創建的Handler對象,就能夠通過該對象向父線程的消息隊列發送消息了。

因為Android要求在UI線程中更新界面,因此,能夠通過該方法在其他線程中更新界面。

子線程更新UI實例:

步驟:

1、創建Handler對象(此處創建於主線程中便於更新UI)。

2、構建Runnable對象。在Runnable中更新界面。

3、在子線程的run方法中向UI線程post,runnable對象來更新UI。

具體代碼例如以下:

package djx.android;

import djx.downLoad.DownFiles;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class downLoadPractice extends Activity {
	private Button button_submit=null;
	private TextView textView=null;
	private String content=null;
	private Handler handler=null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //創建屬於主線程的handler
        handler=new Handler();
        
        button_submit=(Button)findViewById(R.id.button_submit);
        textView=(TextView)findViewById(R.id.textView);
        button_submit.setOnClickListener(new submitOnClieckListener());
    }
    //為按鈕加入監聽器
    class submitOnClieckListener implements OnClickListener{
		@Override
		public void onClick(View v) {
//本地機器部署為server。從本地下載a.txt文件內容在textView上顯示			
			final DownFiles df=new DownFiles("http://192.168.75.1:8080/downLoadServer/a.txt");
			textView.setText("正在載入......");
			new Thread(){
				public void run(){	
					content=df.downLoadFiles();		
					handler.post(runnableUi); 
					}					
			}.start();						
		}
    	
    } 

   // 構建Runnable對象。在runnable中更新界面
    Runnable   runnableUi=new  Runnable(){
		@Override
		public void run() {
			//更新界面
			textView.setText("the Content is:"+content);
		}
    	
    };
    	
    
}


 

參考網址:

1. http://blog.csdn.net/djx123456/article/details/6325983

2. 具體線程具體解釋鏈接http://lavasoft.blog.51cto.com/62575/27069/

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM