【发布时间】:2015-01-13 00:55:46
【问题描述】:
如何使用在另一个线程(不是主线程)和不同类中定义的方法?直接示例是在 AndroidDev 上的蓝牙教程中有一个 ConnectedThread 类 在该类中有一个 write() 方法,用于将某些内容放在蓝牙的输出流上。我如何在主要活动中使用该方法,因为我想通过按下按钮发送信息?
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) { }
}
}
【问题讨论】:
-
你的问题有点混乱-线程中没有定义函数。它们在类中定义。任何函数都可以在任何线程上调用,尽管这样做可能会导致系统其他地方出现问题,这是合法的 Java。
标签: java android multithreading bluetooth