咖啡伴侶

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

          Android 簡(jiǎn)單UI開發(fā) -5

          Posted on 2010-02-04 18:18 oathleo 閱讀(273) 評(píng)論(0)  編輯  收藏
          Android線程安全問題:

                button2.setOnClickListener(new OnClickListener() {
                     ......
               });
          加了個(gè)監(jiān)聽,里面起Timer,定時(shí)修改數(shù)據(jù)。
          發(fā)現(xiàn)Log一直在打,View無變化。
          估計(jì)線程出了問題。類似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.


          解決辦法和我預(yù)計(jì)的一樣:

          1.在Invalidate處調(diào)用 postInvalidate,命名上可以參數(shù)肯定是把當(dāng)前的timer線程排隊(duì)到UI線程去。不過對(duì)于我不是很適用,畢竟UI不希望讓用戶自己去Invalidate

          2.既然不能去排隊(duì),那就干脆把自己改造成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+" );//不一定是顯式的調(diào)用修改UI的語句
                                      }
                                  });
                              }
                          },1000,3000);   


          OK!


           


          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 桃园县| 屏东市| 长武县| 杭锦旗| 贺兰县| 太湖县| 化州市| 太白县| 沁阳市| 马尔康县| 延川县| 绥阳县| 浠水县| 蒙山县| 长沙市| 高唐县| 鞍山市| 正定县| 营山县| 新巴尔虎左旗| 普兰店市| 澎湖县| 巢湖市| 贵定县| 林甸县| 达日县| 舒兰市| 廉江市| 甘谷县| 朔州市| 云霄县| 嘉峪关市| 集安市| 绥芬河市| 新郑市| 龙门县| 浮梁县| 永兴县| 平南县| 十堰市| 静安区|