Android開(kāi)發(fā)中經(jīng)常使用后臺(tái)線程做些耗時(shí)的工作麻裳,任務(wù)完成后可以通過(guò)以下4種方法來(lái)更新ui界面口蝠。對(duì)應(yīng)的函數(shù)功能說(shuō)明附上,以做備份津坑。
1妙蔗、Activity.runOnUiThread(Runnable action)
Runs the specified action on the UI thread. If the current thread is the UI
* thread, then the action is executed immediately. If the current thread is
* not the UI thread, the action is posted to the event queue of the UI thread.
2、View.post(Runnable action)
Causes the Runnable to be added to the message queue.
* The runnable will be run on the user interface thread.
類(lèi)似的方法包括View.postDelayed(Runnable action, long delayMillis)來(lái)延時(shí)觸發(fā)ui事件
3疆瑰、Handler.sendMessage(Message msg)
Pushes a message onto the end of the message queue after all pending messages
* before the current time. It will be received in {@link #handleMessage},
* in the thread attached to this handler.
注意眉反,Handler必須在ui線程中初始化(Handler handler = new Handler())昙啄,或者調(diào)用Handler mainHandler = new Handler(Looper.getMainLooper())
Message創(chuàng)建時(shí),推薦使用以下方法寸五,提高創(chuàng)建效率:
Message msg = mainHandler.obtainMessage();
Message mst = Message.obtain();
//Message的參數(shù)解析如下
msg.what = 1000; //消息標(biāo)識(shí)梳凛。每個(gè)handler有各自的命名空間,可以不必?fù)?dān)心沖突
msg.arg1=2; //存放整形數(shù)據(jù)梳杏,如果攜帶數(shù)據(jù)簡(jiǎn)單韧拒,優(yōu)先使用arg1和arg2,比Bundle更節(jié)省內(nèi)存十性。
msg.arg2=3; //存放整形數(shù)據(jù)
Bundle bundle=new Bundle();
bundle.putString("dd","adfasd");
bundle.putInt("love",5);
msg.setData(bundle);
msg.obj=“test”; //用來(lái)存放Object類(lèi)型的任意對(duì)象叛溢。使用messenger跨進(jìn)程傳消息時(shí),需要實(shí)現(xiàn)Parcelable接口
發(fā)送消息的其他方法:
1)sendEmptyMessage(int what); //發(fā)送設(shè)置了what消息標(biāo)志的空消息
2)sendEmptyMessageAtTime(int what, long uptimeMillis); //定時(shí)發(fā)送空消息
3)sendEmptyMessageDelayed(int what, long delayMillis); //延時(shí)發(fā)送空消息
4)sendMessageAtTime(Message msg, long uptimeMillis); //定時(shí)發(fā)送消息
5)sendMessageDelayed(Message msg, long delayMillis); //延時(shí)發(fā)送消息
6)sendMessageAtFrontOfQueue(Message msg); //最先處理消息(慎用)
4烁试、Handler.post(Runnable r)
Causes the Runnable r to be added to the message queue.
* The runnable will be run on the thread to which this handler is attached.
注意,Handler必須在ui線程中初始化(Handler handler = new Handler())拢肆,或者調(diào)用Handler mainHandler = new Handler(Looper.getMainLooper())
類(lèi)似的方法還有:
1)postAtTime(Runnable r, long uptimeMillis); //在某一時(shí)刻發(fā)送消息
2)postAtDelayed(Runnable r, long delayMillis); //延遲delayMillis毫秒再發(fā)送消息