Send data through bluetooth programmatically
I need to send data from my android phone to the android emulator that is in my PC through Bluetooth functionality. I understand there's a need of using the client and server side function. However, I don't understand how to invoke my methods into the onCreate function through these codes:
public BluetoothSocketActivity(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocke开发者_如何学Pythont is final
BluetoothSocket tmp = null;
remoteDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
} catch (IOException e) { }
mmSocket = tmp;
}
public void runConnect() {
// Cancel discovery because it will slow down the connection
_bluetooth.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket);
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(BluetoothDeviceTest.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
private void manageConnectedSocket(BluetoothSocket mmSocket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
The android emulator does not support bluetooth. You can see this stackoverflow post for an optional library to install to emulate bluetooth over a TCP connection.
精彩评论