如何使用另一个线程(非主要)和另一个类中定义的方法?直接示例是在蓝牙教程onAndroidDev中有一个ConnectedThread类 并且在该类中有一个write()方法,用于在bluetooth的输出流上放置一些东西。如何在main activiy中使用该方法,因为我想通过按下按钮发送信息?
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) { }
}
}
答案 0 :(得分:0)
确保您尝试从另一个类访问的方法是公共方法。
答案 1 :(得分:0)
在此示例中,主要活动调用fragmentActivity并在布局主要活动中显示片段。您需要做的是在 layout fragmentActivity 中创建一个新按钮,并在 onViewCreated 中实例化。按钮在setupChat ()
方法中初始化事件后,通过参数发送sendMessage ("yourMessage")
您的信息。片段活动中的所有内容。
答案 2 :(得分:-1)
我建议使用诸如EventBus或Otto之类的eventbus
。如果要更改UI,则需要注册该事件,然后在主线程上运行代码,例如Activity.runOnUIThread(){}