1. 程式人生 > >錯誤:Only the original thread that created a view hierarchy can touch its views——Handler的使用(更新UI介面)

錯誤:Only the original thread that created a view hierarchy can touch its views——Handler的使用(更新UI介面)

今天寫了一個更新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  and Runnable objects associated with a thread's . 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。

詳細程式碼如下:

  1. package djx.android;  
  2. import djx.downLoad.DownFiles;  
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.os.Handler;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9. import android.widget.TextView;  
  10. public class downLoadPractice extends Activity {  
  11.     private Button button_submit=null;  
  12.     private TextView textView=null;  
  13.     private String content=null;  
  14.     private Handler handler=null;  
  15.     /** Called when the activity is first created. */  
  16.     @Override  
  17.     public void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.         //建立屬於主執行緒的handler  
  21.         handler=new Handler();  
  22.         button_submit=(Button)findViewById(R.id.button_submit);  
  23.         textView=(TextView)findViewById(R.id.textView);  
  24.         button_submit.setOnClickListener(new submitOnClieckListener());  
  25.     }  
  26.     //為按鈕新增監聽器  
  27.     class submitOnClieckListener implements OnClickListener{  
  28.         @Override  
  29.         public void onClick(View v) {  
  30. //本地機器部署為伺服器,從本地下載a.txt檔案內容在textView上顯示           
  31.             final DownFiles df=new DownFiles("http://192.168.75.1:8080/downLoadServer/a.txt");  
  32.             textView.setText("正在載入......");  
  33.             new Thread(){  
  34.                 public void run(){    
  35.                     content=df.downLoadFiles();       
  36.                     handler.post(runnableUi);   
  37.                     }                     
  38.             }.start();                        
  39.         }  
  40.     }   
  41.    // 構建Runnable物件,在runnable中更新介面  
  42.     Runnable   runnableUi=new  Runnable(){  
  43.         @Override  
  44.         public void run() {  
  45.             //更新介面  
  46.             textView.setText("the Content is:"+content);  
  47.         }  
  48.     };  
  49. }  

相關推薦

錯誤Only the original thread that created a view hierarchy can touch its views——Handler的使用更新UI介面

今天寫了一個更新UI的小例子,沒想到出了log列印了這樣一個錯誤:Only the original thread that created a view hierarchy can touch its views。goolgle了一下找到了原因。 原來android中相關

Android: Only the original thread that created a view hierarchy can touch its views 異常

action 接收 如果 exc void 簡單使用 idg ror ucc 最近自己再寫一個小項目練手,創建一個線程從網絡獲取數據然後顯示在 recyclerView 上。寫好後發現頁面能夠顯示,但是有時候會把請求的數據顯示過來,有時候不會。點開 android moni

Error:Only the original thread that created a view hierarchy can touch its views

記錄: 錯誤:Only the original thread that created a view hierarchy can touch its views 在子執行緒更新UI 自己的手機型號為榮耀9青春版,不會出現這個問題,可是有的手機會出現這個問題 解決方法

子執行緒呼叫invalidate()產生“Only the original thread that created a view hierarchy can touch its views.”原因分析

[TOC] 備註:本文基於sdk28, **ViewActivity頁面禁用了硬體加速(AndroidManifest.xml中添加了android:hardwareAccelerated="false")**。 # 1、異常出處 ViewActivity程式碼連結:https://gitee.com/282

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a v

public class MainActivity extends AppCompatActivity { private Button mButton; private TextVi

Qt5執行緒錯誤QThread: Destroyed while thread is still running

背景:         當前類,編寫接收子執行緒類訊號的槽函式和觸發子執行緒類執行的訊號;         新建一個子執行緒類,編寫槽函式和訊號,MyClass *m_MyClass=new MyClass();         新建一個執行緒物件QThread *runT

Qt5線程錯誤QThread: Destroyed while thread is still running執行runThread->exit(0)

文章 原創 delete class 函數 開啟 mov runt 連接 背景: 當前類,編寫接收子線程類信號的槽函數和觸發子線程類執行的信號; 新建一個子線程類,編寫槽函數和信號,MyClass *m_MyClass=new MyCla

用idea+maven編譯打包spark project core錯誤java.lang.RuntimeException: Unable to load a Suite class

ide exception 5-0 sco anon time arp create run Discovery starting. *** RUN ABORTED *** java.lang.RuntimeException: Unable to load a Su

搭建elasticsearch叢集報錯with the same id but is a different node instance]; ]

記錄一下在安裝 elastic-search 單機多節點是時候報錯解決方案。 [INFO ][o.e.d.z.ZenDiscovery ] [slave-one] failed t o send join request to master [{mast

Android 錯誤Throwing OutOfMemoryError "Failed to allocate a 898716 byte allocation with

1.首先Throwing OutOfMemoryError 絕大部分是記憶體溢位,首先確保你的手機是否記憶體足夠執行該軟體 2.儘量不要將context、activity寫成靜態很容易錯亂 3.每個活動可以指定不同的載入模式 這裡有一篇文章寫的很詳細https://www.jianshu.c

mysql 錯誤Field '欄位' doesn't have a default value

當提示某個欄位沒有預設值時,解決辦法就是為該欄位設定預設值。 但是糾其原因是mysql的嚴格模式的問題。 我們本地開發可能使用了非嚴格模式 配置檔案:   linux中my.cnf   win

matlab的plot呼叫函式不能用了,總出現錯誤Attempt to execute SCRIPT plot as a function

問題解決: 查詢當前目錄下,可能有一個plot.m指令碼。刪掉或重新命名即可。 注意:儲存圖片名稱時不要存為plot.m,因為matlab中plot函式的指令碼檔案就是plot.m,要防止該檔案為重新

微信支付手機系統自帶的瀏覽器,調用微信支付如何實現非掃碼

所有 價格 驗證 返回 調用 -i 是否為空 支付申請 data- Q:翻看了微信支付的api沒發現支持h5調支付接口的情況(微信js除外),然後卻發現美團的支付成功調用了,這是怎麽實現的? A: 使用微信H5支付即可。H5支付通過URL調起微信APP,

題解報告hdu 2188 悼念512汶川大地震遇難同胞——選拔誌願者巴什博弈

desc 考核 解題思路 bsp c代碼 字符串 每次 代碼 ont 題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=2188 Problem Description 對於四川同胞遭受的災難,全國人民紛紛伸出援助之手,幾乎每個省

群暉(黑) 篇四申請免費SSL證書以及用群暉套件搭建郵件服務器可以收藏的

智能 等待 默認項目 家用路由器 asq 地方 服務器搭建 復制 for 轉載的文章 群暉(黑) 篇四:申請免費SSL證書以及用群暉套件搭建郵件服務器 前言這個系列是關於群暉常用套件的使用記錄,前兩篇討論了監控中心,虛擬機,

《TensorFlow實戰Google深度學習框架》--5.2.1 MNIST手寫識別問題程式已改進

目錄 MNIST資料集介紹: TensorFlow完整訓練MNIST資料集(程式已改進): 本篇部落格涉及很多本書第4章的知識:啟用函式、指數衰減的學習率設定、正則化、滑動平均等知識。如有疑問請參考本部落格關於第4章記錄介紹。 MNIST資料集介紹: MNIST資料集是N

《TensorFlow實戰Google深度學習框架》——6.3 卷積神經網路常用結構池化層

池化層在兩個卷積層之間,可以有效的縮小矩陣的尺寸(也可以減小矩陣深度,但實踐中一般不會這樣使用),co。池從而減少最後全連線層中的引數。 池化層既可以加快計算速度也可以防止過度擬合問題的作用。 池化層也是通過一個類似過濾器結構完成的,計算方式有兩種: 最大池化層:採用最

淺析微信支付公眾平臺卡券功能開通、HTML5線上發券JS-SDK介面、檢視卡券詳情

本文是【淺析微信支付】系列文章的第十六篇,主要講解如何使用微信公眾平臺的卡券功能、如何使用HTML5在網頁展示使用者領券以及微信卡券和商戶平臺代金券的關係。 淺析微信支付系列已經更新十六篇了喲~,沒有看過的朋友們可以看一下哦。 淺析微信支付:開通免充值產品功能及如何進行介面升級指引 淺析微

Jsoup實現java專案的服務端之間的通訊 需要開放介面

@Override public Map<String, Object> getbarrierInfoCount(Map<String, Object> param, String signType) throws Exception { Co

Android非同步處理二使用AsyncTask非同步更新UI介面

在《Android非同步處理一:使用Thread+Handler實現非UI執行緒更新UI介面》中,我們使用Thread+Handler的方式實現了非同步更新UI介面,這一篇中,我們介紹一種更為簡潔的實現方式:使用AsyncTask非同步更新UI介面。 概述: