咖啡伴侣

呆在上海
posts - 163, comments - 156, trackbacks - 0, articles - 2

Android 简单UI开发 -5

Posted on 2010-02-04 18:18 oathleo 阅读(268) 评论(0)  编辑  收藏
Android线程安全问题:

      button2.setOnClickListener(new OnClickListener() {
           ......
     });
加了个监听,里面起Timer,定时修改数据。
发现Log一直在打,View无变化。
估计线程出了问题。类似Swing的线程安全问题。
接着Google.....


The best thing is to  use Handler with delayed messages.
And Timer works fine, the problem is that a Timer runs in a separate thread,   and so you are trying to modify a view owned by another thread (the main   thread that originally created it).

What I think is happening is you're falling off the UI thread. There is a single "looper" thread which handles all screen updates. If you attempt to call "invalidate()" and you're not on this thread nothing will happen.

Try using "postInvalidate()" on your view instead. It'll let you update a view when you're not in the current UI thread.


解决办法和我预计的一样:

1.在Invalidate处调用 postInvalidate,命名上可以参数肯定是把当前的timer线程排队到UI线程去。不过对于我不是很适用,毕竟UI不希望让用户自己去Invalidate

2.既然不能去排队,那就干脆把自己改造成UI线程吧。借助android.os.Handler

          final Handler handler = new Handler();
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    public void run() {
                        handler.post(new Runnable() {
                            public void run() {
                                 root.setName(new Date() + "Root+" );//不一定是显式的调用修改UI的语句
                            }
                        });
                    }
                },1000,3000);   


OK!


 


只有注册用户登录后才能发表评论。


网站导航: