咖啡伴侶

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

          Android 簡單UI開發 -5

          Posted on 2010-02-04 18:18 oathleo 閱讀(279) 評論(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!


           


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 黔东| 昂仁县| 尉犁县| 武清区| 英超| 嘉鱼县| 西华县| 嵊州市| 乌拉特前旗| 达拉特旗| 凌源市| 海盐县| 乾安县| 南汇区| 乳山市| 惠东县| 弋阳县| 雷山县| 清丰县| 建阳市| 牙克石市| 日喀则市| 梁平县| 穆棱市| 商洛市| 樟树市| 三江| 遵义县| 宝应县| 沐川县| 平定县| 松潘县| 柘城县| 泾源县| 天长市| 将乐县| 嵩明县| 博湖县| 杭锦后旗| 句容市| 襄城县|