如何在多个活动中使用Connected Thread

时间:2014-03-11 12:34:06

标签: java android multithreading sockets bluetooth

我是Android的新手。首先,我编写了一个应用程序,通过蓝牙连接到另一个设备,然后使用套接字和连接线程发送和接收数据。使用一个活动时,一切都很好,我使用处理程序接收数据。 然后我开始用多个活动创建一个应用程序,所以我为socket连接和连接线程创建了一个特殊的类。我通常从任何活动发送数据,但我不知道如何收到答案(如何在许多活动中制作处理程序,或者使用什么替代方法)。你可以帮助我写下这行代码,我应该补充一下。

感谢。

这是我的主题:

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;

          try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
          }
          catch (IOException e) {}

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
          }
          public void run() {
            byte[] buffer = new byte[256];
            int bytes;
            while(true) {
              try {
                bytes = mmInStream.read(buffer);

                byte[] readBuf = (byte[]) buffer;
                String strIncom = new String(readBuf, 0, bytes);

                  // Here I need some method to send data to activity
              }
              catch (IOException e) {
                  break;
                }
              }
            }

              public void write(String message) { 
            byte[] msgBuffer = message.getBytes();
                try {
                    mmOutStream.write(msgBuffer);
                } catch (IOException e) {

                  }

          }

}

1 个答案:

答案 0 :(得分:0)

嗯,你可以做的一件事是使用Interface

,例如:

public class ConnectedThread extends Thread {
// You declare your interface in the Class body
    public static interface CallBackListener
    {
        public void onReceived(String msg);
    }

   private final BluetoothSocket mmSocket;
   private final InputStream mmInStream;
   private final OutputStream mmOutStream;
   private CallBackListener listener = null;

// then, those who want to use this class must implement 
// this interface
   public ConnectedThread(BluetoothSocket socket, CallBackListener aListener) 
   {        
         this.listener = aListener;
         ... 

在线程的run方法中你喜欢这样:

// Here I need some method to send data to activity
if (listener != null)
{
   listener.onReceived(strIncom);
}

当你创建课程时,请这样做:

BluetoothSocket socket = null;
/*
* Create the BlueToothSocket here
   BluetoothSocket socket = new BluetoothSocket(...);
*/

ConnectedThread conThread = new ConnectedThread(socket, new ConnectedThread.CallBackListener()
{
   @Override
   public void onReceived(String msg)
   {
    // here you'll receive the string msg
    // keep in mind that you receive this call 
    // in the ConnectedThread's context, not the UI thread
   }
});