2017-02-27 69 views
2

如何在UI線程和後臺線程之間進行線程間通信?我想在這裏使用通用處理程序的概念來更新我的UI。 我有這個概念如下UI線程和使用處理程序的其他線程之間的通信

new Thread(new Runnable() { 
     public void run() { 
      while (mProgressStatus < 100) { 
       mProgressStatus = doWork(); 

       // Update the progress bar 
       mHandler.post(new Runnable() { 
        public void run() { 
         mProgress.setProgress(mProgressStatus); 
        } 
       }); 
      } 
     } 
    }).start(); 

我想用兩個班,一個類包含主線程,另一個類包含後臺線程,它們使用相同的處理程序。我如何實現這一點? 我知道這很常見,但我發現很難準確實施。

回答

1

如果您不想使用靜態概念,則可以傳遞參數中的任何內容。在下面的代碼中,我已經實現了兩個類。正如你所問,我在兩個線程類中都使用了通用處理程序。我將處理程序h1作爲Runnable對象的參數和start()方法傳遞給另一個線程類的run()方法。包含run()方法的線程是UI(Main)線程。我們必須使用UI線程來更新UI。工作者(後臺)線程無法做UI更新。工人與UI之間的通信是通過處理程序完成的。所以,我在UI線程類中定義了處理程序h2。當從後臺線程類調用UI線程類構造函數時,我從構造函數獲取來自h1的h2值。我用h2進行溝通。實際上,h2和h1屬於系統中相同的內存空間。

我在兩個類下面做了線程通信供您參考。

一流

public class MainActivity extends AppCompatActivity { 
    Handler h1; 
    Thread t; 
    EditText editText; 
    private Bundle bb = new Bundle(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     editText = (EditText) findViewById(R.id.editText); 

     h1 = new Handler(Looper.getMainLooper()) { 

      @Override 
      public void handleMessage(Message msg) { 
       bb = msg.getData(); 
       String str = bb.getString("udd"); 
       editText.setText(str); 
       System.out.println(str); 
      } 
     }; 
     t = new Thread(new MyRunnable(h1)); //I pass Runnable object in thread so that the code inside the run() method 
     //of Runnable object gets executed when I start my thread here. But the code executes in new thread 
     t.start(); //thread started 

     try { 
      t.sleep(1000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 


    } 

} 

二等

public class MyRunnable implements Runnable { 
    private Handler h2; 
    public MyRunnable(Handler h) { 
     this.h2 = h; 
    } 

    @Override 
    public void run() { 

     //everything inside rum method executes in new thread 
     for(int i=0;i<10;i++) { 
      Message m = Message.obtain(); //get null message 
      Bundle b = new Bundle(); 
      b.putString("udd", "daju"); 
      m.setData(b); 
      //use the handler to send message 
      h2.sendMessage(m); 

     } 
    } 
} 

注意:當thread.start()發生時,它觸發了Runnable類的運行,它會創建一個單獨的線程。所以每次調用start()時,都會有一個與被調用者線程具有相同優先級的新線程。

希望,這對你有幫助。

+0

謝謝!它爲我工作。 – Gokul

+0

我很高興男士@ gd16 –