gpt4 book ai didi

java - 如何从主 Activity 调用android蓝牙ConnectedThread类的write()函数

转载 作者:太空宇宙 更新时间:2023-11-04 13:40:22 24 4
gpt4 key购买 nike

我只是想知道如何从主 Activity java文件中调用ConnectedThread类的写入函数

public static class ConnectedThread extends Thread {
public 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);
// Send the obtained bytes to the UI activity
// mHandler.obtainMessage(2, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}

// Call this from the main activity to send data to the remote device
public void write(String m) {
try {
String msg = m;
mmOutStream.write(msg.getBytes());
} catch (Exception e)
{
e.printStackTrace();
}

}

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

最佳答案

简短的回答是,您不能(也不应该)直接从绑定(bind)到主线程的 Activity 回调或 Handler 调用它。这将导致应用程序的主线程阻塞,因为您正在进行套接字调用。将其推迟到后台线程。为此,您可以使用许多选项,例如 HandlerThread、IntentService、AsyncTask 甚至 RxJava 框架。

关于java - 如何从主 Activity 调用android蓝牙ConnectedThread类的write()函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31291957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com