Java 在Android中从不同的线程调用方法
如何使用在另一个线程(非主线程)和其他类中定义的方法?直接示例是AndroidDev上的蓝牙教程中有一个ConnectedThread类 在该类中有一个write()方法,用于将某些内容放到bluetooth的输出流中。我如何在主活动中使用该方法,因为我想通过按下按钮发送信息Java 在Android中从不同的线程调用方法,java,android,multithreading,bluetooth,Java,Android,Multithreading,Bluetooth,如何使用在另一个线程(非主线程)和其他类中定义的方法?直接示例是AndroidDev上的蓝牙教程中有一个ConnectedThread类 在该类中有一个write()方法,用于将某些内容放到bluetooth的输出流中。我如何在主活动中使用该方法,因为我想通过按下按钮发送信息 private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final In
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);
// Send the obtained bytes to the UI activity
mHandler.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) { //how do i use this method in the ui(main) activity?
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) { }
}
}
确保您试图从另一个类访问的方法是公共方法。我建议使用
eventbus
,例如eventbus或Otto。如果要更改UI,则需要注册事件,然后在主线程上使用类似于Activity.runOnUIThread(){}
的内容运行代码。在本例中,main Activity调用fragmentActivity,并在布局主活动中显示片段。您需要做的是在layout fragmentActivity中创建一个新按钮,并在onViewCreated中实例化。在按钮初始化setupChat()
方法中的事件后,通过参数发送sendMessage(“yourMessage”)
您的信息。片段活动中的所有内容。可能重复?您的问题有点混乱-函数未在线程中定义。它们是在类中定义的。任何函数都可以在任何线程上调用,尽管这样做可能会在系统的其他地方引起问题,因为Java是合法的。