2015-09-18

来源:互联网 发布:薛之谦 离婚 知乎 编辑:程序博客网 时间:2024/04/30 08:11

android中使用线程对界面的修改

若需使用循环线程对界面进行修改时(如歌曲进度条,当前播放时间。。。),启动线程时最好启用runOnUiThread()方法对界面进行修改,因为如果不这样做就会造成线程阻塞,不然就要使用post等方法(http://blog.csdn.net/u012810034/article/details/48353731)),还是推荐使用runOnUiThread()。
看API解释:
runOnUiThread():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.
大概是说
在UI线程上运行指定的动作。如果当前线程是UI线程,那么行动是立即执行。如果当前线程不是UI线程,操作是发布到UI线程的事件队列。
意思就是会有个UI线程专门执行对UI 的操作,不用我们自己创建线程。、
示例:

//此为在主线程中通过按钮触发的线程Runnable runnableSetMusicCurrentSeek = new Runnable() {        @Override        public void run() {            //获取服务中的歌曲的当前刻度            final int seek = sub.getMusicCurrentSeek();            //更新UI            MainActivity.this.runOnUiThread(new Runnable() {                @Override                public void run() {//这里对UI的操作会添加到UI线程,不会造成线程阻塞                    //设置文本的当前刻度                    txMusicSeek.setText(DateFormat.format("mm:ss", seek));                    //设置seekBar的当前刻度                    musicSeekBar.setProgress(seek);                }            });        }    };
0 0