咖啡伴侶

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

          Android 簡單UI開發 -5

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


           


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


          網站導航:
           
          主站蜘蛛池模板: 宜章县| 赣州市| 科技| 炎陵县| 中方县| 孝感市| 平江县| 高邮市| 凤阳县| 铁岭市| 鄂温| 沙洋县| 三门峡市| 淮滨县| 密云县| 美姑县| 宝坻区| 垣曲县| 水城县| 满城县| 淄博市| 武山县| 个旧市| 盐城市| 定陶县| 江华| 东乌珠穆沁旗| 肇东市| 阳东县| 色达县| 安康市| 澄城县| 长阳| 彭阳县| 兴仁县| 永靖县| 甘德县| 双峰县| 呼和浩特市| 阿克苏市| 曲水县|