2014-09-23 115 views
0

我有一個線程內運行的代碼。我試圖使用處理程序來接收來自線程的消息,以便我可以更新UI。不幸的是,該消息沒有發送給處理程序。Android上的Handler沒有收到消息

這是主題

    ChromaticLayout chromatic = new ChromaticLayout(mPartition, mDeviceWidth, mDeviceHeight, mData); 
        chromatic.execute(new ChromaticLayout.LayoutCallback() { 

         @Override 
         public synchronized void retrieveResult(Object[][] data) { 
          // TODO Auto-generated method stub 
          mPhotoData.clear(); 
          Log.w("CALLBACK", "start"); 

          for (int i=0; i<data.length; i++) 
          { 
           PhotoFrameData[] row = new PhotoFrameData[data[i].length]; 

           for (int j=0; j<data[i].length; j++) { 
            if (j==0) 
            Log.w("CALLBACK", "Width = " + ((PhotoFrameData) data[i][j]).getRectangle().width() + " height = " + ((PhotoFrameData) data[i][j]).getRectangle().height()); 

            row[j] = (PhotoFrameData) data[i][j]; 
           } 
           mPhotoData.add(row); 

          } 
          Log.w("CALLBACK", "end"); 

          PhotoFrameAdapter.this.handle.post(new Runnable(){ 

           @Override 
           public void run() { 
            // TODO Auto-generated method stub 
            PhotoFrameAdapter.this.handle.sendEmptyMessage(1); 
           } }); 
          //if (!PhotoFrameAdapter.this.handle.sendEmptyMessage(1)) 
          // Log.w("CALLBACK", "Handle not working"); 
         }}); 

       } 

的run方法在我的代碼片段是處理程序的接收消息:

protected Handler handle = new Handler() { 

     public void handleMessage(Bundle message) { 
      //PhotoFrameAdapter.this.notifyDataSetChanged(); 
      mListener.dataLoaded(this); 
     } 
    }; 

什麼使它不添加到消息隊列和呼叫handleMessage?由於

回答

2

試試這個:

private Handler handler = new Handler() { 
     public void handleMessage(Message msg) { 
      switch (msg.what) { 
      case 1: 
       //do staff 
       break; 
      } 
     }; 
    }; 
+0

謝謝,你是對的參數.. – LittleFunny 2014-09-23 23:34:08

1

你可以使用一個處理程序的另一種方法如下(這也許在很多情況下,一個簡單的實現):

定義UI線程上的投手:

private Handler mHandler = new Handler(); 
從後臺線程

然後,只需用後的代碼Runnable要運行:

mHandler.post(new Runnable() { 
    @Override 
    public void run() { 
     // Code to run here 
    } 
});