Android开发中经常使用后台线程做些耗时的工作,任务完成后可以通过以下4种方法来更新ui界面。对应的函数功能说明附上,以做备份。
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.
类似的方法包括View.postDelayed(Runnable action, long delayMillis)来延时触发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()),或者调用Handler mainHandler = new Handler(Looper.getMainLooper())
Message创建时,推荐使用以下方法,提高创建效率:
Message msg = mainHandler.obtainMessage();
Message mst = Message.obtain();
//Message的参数解析如下
msg.what = 1000; //消息标识。每个handler有各自的命名空间,可以不必担心冲突
msg.arg1=2; //存放整形数据,如果携带数据简单,优先使用arg1和arg2,比Bundle更节省内存。
msg.arg2=3; //存放整形数据
Bundle bundle=new Bundle();
bundle.putString("dd","adfasd");
bundle.putInt("love",5);
msg.setData(bundle);
msg.obj=“test”; //用来存放Object类型的任意对象。使用messenger跨进程传消息时,需要实现Parcelable接口
发送消息的其他方法:
1)sendEmptyMessage(int what); //发送设置了what消息标志的空消息
2)sendEmptyMessageAtTime(int what, long uptimeMillis); //定时发送空消息
3)sendEmptyMessageDelayed(int what, long delayMillis); //延时发送空消息
4)sendMessageAtTime(Message msg, long uptimeMillis); //定时发送消息
5)sendMessageDelayed(Message msg, long delayMillis); //延时发送消息
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()),或者调用Handler mainHandler = new Handler(Looper.getMainLooper())
类似的方法还有:
1)postAtTime(Runnable r, long uptimeMillis); //在某一时刻发送消息
2)postAtDelayed(Runnable r, long delayMillis); //延迟delayMillis毫秒再发送消息