Only the original thread that created a view hierarchy can touch its views——Handler的使用
今天寫了一個更新UI的小例子,沒想到出了log打印了這樣一個錯誤:Only the original thread that created a view hierarchy can touch its views。goolgle了一下找到了原因。
原來android中相關的view和控件不是線程安全的,我們必須單獨做處理。這里借此引出Handler的使用。
?
Handler的官方描述:A Handler allows you to send and process?Message?and Runnable objects associated with a thread's?MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue
.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線程中更新界面,因此,可以通過該方法在其它線程中更新界面。
通過Handler更新UI實例:
步驟:
1、創建Handler對象(此處創建于主線程中便于更新UI)。
2、構建Runnable對象,在Runnable中更新界面。
3、在子線程的run方法中向UI線程post,runnable對象來更新UI。
?
詳細代碼如下:
[java] view plaincopypackage 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) {
//本地機器部署為服務器,從本地下載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);
??}
??? ?
??? };
??? ?
???
}
*java線程的詳細講解鏈接?
總結
以上是生活随笔為你收集整理的Only the original thread that created a view hierarchy can touch its views——Handler的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .Android开发在Eclipse环境
- 下一篇: Failed to install .a