Java 如何从主活动调用android bluetooth的ConnectedThread类的write()函数
我只想知道如何从主活动java文件调用Java 如何从主活动调用android bluetooth的ConnectedThread类的write()函数,java,android,android-bluetooth,Java,Android,Android Bluetooth,我只想知道如何从主活动java文件调用ConnectedThread类的write函数 public static class ConnectedThread extends Thread { public final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThr
ConnectedThread
类的write函数
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) { }
}
}
简而言之,您不能(也不应该)直接从绑定到主线程的
活动
回调或处理程序
调用它。这将导致应用程序的主线程阻塞,因为您正在进行套接字调用。将此延迟到后台线程。您可以使用许多选项,例如HandlerThread
,IntentService
,AsyncTask
,甚至可以使用RxJava框架。简而言之,您不能(也不应该)直接从绑定到主线程的活动
回调或处理程序
调用它。这将导致应用程序的主线程阻塞,因为您正在进行套接字调用。将此延迟到后台线程。您可以使用许多选项,例如HandlerThread
、IntentService
、AsyncTask
甚至RxJava框架