咖啡伴侶

          呆在上海
          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!


           


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


          網站導航:
           
          主站蜘蛛池模板: 历史| 海林市| 大竹县| 秦皇岛市| 咸丰县| 武安市| 长葛市| 甘泉县| 皮山县| 宁海县| 宿松县| 永修县| 固始县| 潜山县| 原平市| 兰州市| 思南县| 临高县| 横峰县| 台南市| 绿春县| 巢湖市| 泾源县| 邻水| 北辰区| 广安市| 嘉荫县| 岳阳市| 靖宇县| 垫江县| 长治县| 钟祥市| 龙陵县| 专栏| 赣榆县| 河南省| 宁阳县| 大荔县| 金沙县| 香格里拉县| 巢湖市|