如何在多个活动中使用连接的线程

jrcvhitl  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(354)

我是android的新手。首先,我编写了一个应用程序,它通过蓝牙连接到另一个设备,然后使用套接字和连接线程发送和接收数据。当使用一个活动时,一切都很好,我使用handler接收数据。然后我开始创建一个包含多个活动的应用程序,所以我为socket连接和connected线程创建了一个特殊的类。我通常从任何活动发送数据,但我不知道如何接收答案(如何在许多活动中生成处理程序,或者使用什么替代方法)。你能帮我写这行代码吗,我应该加上。
谢谢。
这是我的线索:

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) {

                  }

          }

}

lokaqttq

lokaqttq1#

你能做的一件事就是使用 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
   }
});

相关问题