-
new?Thread?(){ ????public?void?run(){//這個run方法是在子線程中 ????????try{ ????????????Thread.sleep(1000); ????????????handler.post(new?Runnable(){ ????????????????@Override ????????????????public?void?run(){ ????????????????????textView.setText("updata?thread");//這個run()方法是在主線程中的 ????????????????} ????????????},1000);//使用Handler在主線程更新UI ????????}catch(InterruptedException?e){ ????????????e.printStackTrace(); ????????} ????} }.start();
查看全部 -
Android在設計的時候就封裝了一套消息創建,傳遞,處理機制,如果不遵循這樣的機制就沒辦法更新UI信息的,就會拋出異常信息
查看全部 -
Handler是Android給我們提供用來更新UI的一套機制,也是一套消息處理機制,我們可以用它來發送消息,也可以用它來處理消息
查看全部 -
android中更新ui四種方式
runonui
view.post(runable)
handler.post()
handler.sendmessage
查看全部 -
自定義線程處理handler方法:
class?MyThread?extends?Thread{ ????public?Handler?handler; ????@Override ????public?void?run()?{ ????????Looper.prepare(); ????????handler?=?new?Handler(){ ????????????@Override ????????????public?void?handleMessage(Message?msg)?{ ????????????????System.out.print("currentThread:"+Thread.currentThread()); ????????????} ????????}; ????????Looper.loop(); ????} }
查看全部 -
綁定了HandlerThread的Looper的Handler里面是可以更新ui的,也可以做耗時操作.它其實就是個線程,所以可以做耗時操作,除此之外由于在線程中調用了Looper.prepare()方法,所以綁定到了主線程從而可以更新UI了。這是我的理解不知道對不對,不過確實是可以更新UI也可以做耗時操作,我在代碼中試過。
查看全部 -
非ui線程真的不能更新ui嗎?答:某種情況下可以。
在oncreate方法中開啟子線程更新ui,在thread沒有休眠的情況下,因為ViewRootImp在activity的onresume方法中創建,在ViewRootImp方法中判斷當前線程是否為主線程,oncreate在onresume之前執行,所以這種情況下,可以進行更新ui操作。查看全部 -
創建handle的時候會跟一個默認的線程綁定,線程中有一個Massagequeue
查看全部 -
handler是android給我們提供的用來更新UI的一套機制,也是一套消息處理的機制,我們可以發送消息,也可以通過它來處理消息
查看全部 -
可以利用有返回值的handleMassage方法截獲發送來的消息,當handleMassage方法的返回值為true時,后面無返回值的handleMassage就不會執行了。
查看全部 -
handler原理
查看全部 -
handler原理
查看全部 -
Handler實現圖片輪播(循環播放) //實現圖片切換 ? ?class MyRunnable implements Runnable { ? ? ? ?@Override ? ? ? ?public void run() { ? ? ? ? ? ?index++; ? ? ? ? ? ?index = index % 3; ? ? ? ? ? ?imageView.setImageResource(images[index]); ? ? ? ? ? ?handler.postDelayed(myRunnable,1000); ? ? ? ?} ? ?} ? ? ? ?//實現更新textView文本文檔 // ? ? ? ?new Thread() { // ? ? ? ? ? ?@Override // ? ? ? ? ? ?public void run() { // ? ? ? ? ? ? ? ?try { // ? ? ? ? ? ? ? ? ? ?Thread.sleep(1000); // ? ? ? ? ? ? ? ? ? ?handler.post(new Runnable() { // ? ? ? ? ? ? ? ? ? ? ? ?@Override // ? ? ? ? ? ? ? ? ? ? ? ?public void run() { // ? ? ? ? ? ? ? ? ? ? ? ? ? ?textView.setText("Update thread!"); // ? ? ? ? ? ? ? ? ? ? ? ?} // ? ? ? ? ? ? ? ? ? ?}); // ? ? ? ? ? ? ? ?} catch (InterruptedException e) { // ? ? ? ? ? ? ? ? ? ?e.printStackTrace(); // ? ? ? ? ? ? ? ?} // ? ? ? ? ? ?} // ? ? ? ?}.start();
查看全部 -
什么是handler
handler就是官方提供的一套更新UI的機制 也是一套消息處理的機制
查看全部 -
--摘自評論區 使用handler時候常遇到的問題(系統拋出的異常): 1. android.view.ViewRootImpl$CalledFromWrongTreadException:Only the original thread that created a view hierarchy can touch its views 2. Can't create handler inside thread that has not called Looper.prepare() 在子線程中創建一個 Handler對象,卻沒有給它指定一個Looper對象的時候,就會拋出該異常。 如圖是第一個異常拋出的原因:checkThread()判斷“當前線程(更新UI的線程)是不是主線程”,如果不是,就拋出該異常。查看全部
舉報