使用Handler在子线程中更新UI

       Android规定仅仅能在主线程中更新UI。假设在子线程中更新UI 的话会提演示样例如如下错误:Only the original thread that created a view hierachy can touch its view((仅仅有原来的线程建立一个视图层次可以触摸它的视图)。java

      仅仅能在主线程中更新UI的缘由是:android中相关的view和控件不是线程安全的,咱们必须单独作处理。android

      有的时候需要再子线程中实现更新UI,如下介绍使用Handler实现线程通讯的特色实现在子线程中更新UI。安全

Handler的使用场合:app

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

      安排messages和runnables在未来的某个时间点运行。post

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

      将action入队以备在一个不一样的线程中运行。即可以实现线程间通讯。比方当你建立子线程时。你可以再你的子线程中拿到父线程中建立的Handler对象,就可以经过该对象向父线程的消息队列发送消息了。.net

由于Android要求在UI线程中更新界面,所以,可以经过该方法在其余线程中更新界面。线程

子线程更新UI实例:code

步骤:

一、建立Handler对象(此处建立于主线程中便于更新UI)。

二、构建Runnable对象。在Runnable中更新界面。

三、在子线程的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/

相关文章
相关标签/搜索