2015-10-01 34 views
0

我已經從運行在同一活動中的線程得到了結果,但在更改活動後,我無法獲得該結果。有什麼方法可以得到這個結果嗎? 我在這裏的主題,我從runOnUiThread如何從Android上的多個活動中獲取運行線程的結果?

private class ConnectedThread extends Thread { 
    private final BluetoothSocket mmSocket; 
    private final InputStream mmInStream; 
    private final OutputStream mmOutStream; 

    public ConnectedThread(BluetoothSocket socket) { 
     mmSocket = socket; 
     InputStream tmpIn = null; 
     OutputStream tmpOut = null; 

     // Get the input and output streams, using temp objects because 
     // member streams are final 
     try { 
      tmpIn = socket.getInputStream(); 
      tmpOut = socket.getOutputStream(); 
     } catch (IOException e) { } 

     mmInStream = tmpIn; 
     mmOutStream = tmpOut; 
    } 

    public void run() { 
     byte[] buffer = new byte[1024]; // buffer store for the stream 
     int bytes; // bytes returned from read() 

     // Keep listening to the InputStream until an exception occurs 
     while (true) { 
      try { 
       // Read from the InputStream 
       bytes = mmInStream.read(buffer); 
       final String s = new String(buffer); 
       runOnUiThread(new Runnable() { 
        public void run() { 
         Toast.makeText(getApplicationContext(), s.toString(), 
           Toast.LENGTH_SHORT).show(); 
         txtcomand.setText(s); 
         intent.putExtra("ct", s); 
        } 
       }); 

       // Send the obtained bytes to the UI activity 
       // .obtainMessage(MESSAGE_READ, bytes, -1, buffer) 
       //   .sendToTarget(); 
      } catch (IOException e) { 
       break; 
      } 
     } 
    } 

    /* Call this from the main activity to send data to the remote device */ 
    public void write(byte[] bytes) { 
     try { 
      mmOutStream.write(bytes); 
     } catch (IOException e) { } 
    } 

    /* Call this from the main activity to shutdown the connection */ 
    public void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { } 
    } 
} 
+0

使用AsyncTask而不是你的線程執行 – mgokgoz

回答

0

結果您可以定義不同的activitys或類之間進行通信的接口。

只需使用允許傳遞所需數據的方法創建接口即可。

然後在接收器活動上實現它,當您創建第二個活動時,需要傳遞接收器活動的實例並存儲它。

然後,您可以調用該方法並在需要時傳遞任何參數。

希望這會有所幫助。

+0

你能給我一些接口的例子嗎? –

0

我會建議實現一個服務類,而不是使用線程進行套接字通信。服務可以獨立於您的活動運行,不同的活動可以通過多種方式與您的服務進行通信。

例如,我將執行服務和事件總線,如Otto(http://square.github.io/otto/) - 它的幾行代碼實現。然後你可以發送你的結果而不用擔心活動,你的活動/片段可以訂閱這些活動。它是您的案例中最簡單/最安全的溝通方式,IMO,您將擁有一個很好的模塊化系統。

順便說一句,如果你仍然想使用你的線程,你可以添加事件總線,並將其用於通信。

還有其他方法可以傳遞這些數據。接口,例如,廣播接收器...

相關問題