1
所以我對Java很新,所以要溫柔。 我想通過藍牙連接兩部手機。我創建了一個套接字,但我應該如何使用它?我的意思是,藍牙教程說我應該調用public void write(byte [] bytes)來發送數據,但是如何?我創建了按鈕,分配了「onClick」方法,但是什麼呢?我應該如何調用ConnectedThread窗體UI線程中的方法?下面是來自教程 的示例私有類ConnectedThread extends Thread最終的BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream;如何調用線程方法
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
Message msg = mainHandler.obtainMessage();
Bundle bundle = new Bundle();
String btnTxt = "Socket aquizaired";
bundle.putString("myKey", btnTxt);
msg.setData(bundle);
mainHandler.sendMessage(msg);
// 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) {
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) { }
}
}
,並在UI線程我有類似的財產以後
private void sendSms(){ // method assigned to button "onClick"
// i want to send some text here, like "hello" or something...
//???????????????????????????
}
您需要創建一個線程並將參數傳遞給SendSms – Charlie