I'm trying to connect to a device with the code below... basically modified from the BTchat source. Everything seems to go fine, but the device is not responding to commands, my phone still says it's paired but not connected, and the device says it's not connected. That makes me pretty sure that it's indeed not connected, but no errors are happening.
Could I have the wrong UUID?
the log says:
04-30 18:51:10.116: DEBUG/BluetoothService(1228): uuid(application): 00001101-0000-1000-8000-00805f9b34fb 1
04-30 18:51:10.116: DEBUG/BluetoothService(1228): Making callback for 00001101-0000-1000-8000-00805f9b34fb with result 1
04-30 18:51:10.131: VERBOSE/BluetoothEventRedirector(31561): Received android.bleutooth.device.action.UUID
and my code is printing to the log that it's connected:
04-30 18:53:21.210: DEBUG/BTComm(1044): connect to: K4500-620963
04-30 18:53:21.225: INFO/BTComm(1044): BEGIN ConnectThread
04-30 18:53:26.272: DEBUG/BTComm(1044): connected to: K4500-620963
04-30 18:53:26.272: DEBUG/BTComm(1044): create ConnectedThread
04-30 18:53:26.280: DEBUG/BTComm(1044): setState() 0 -> 3
04-30 18:53:26.280: INFO/BTComm(1044): BEGIN ConnectedThread
Here is my whole code: p
ublic class BTCom {
// Debugging
private static final String TAG = "BTComm";
private static final boolean D = true;
private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Member fields
private final BluetoothAdapter adapter;
private final Handler handler;
private ConnectThread connectThread;
private ConnectedThread connectedThread;
private int state;
private Context context;
private BluetoothDevice BTDevice;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
public BTCom(Context context, Handler handler) {
adapter = BluetoothAdapter.getDefaultAdapter();
state = STATE_NONE;
this.handler = handler;
this.context = context;
}
private void checkBluetooth(){
// check if device supports bluetooth
if (adapter == null) {
Toast.makeText(context, "ERROR: This device does not support Bluetooth communication"
, Toast.LENGTH_LONG).show();
return;
}
// now make sure bluetooth is enabled
if (!adapter.isEnabled()) {
// if not, then prompt the user
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
context.startActivity(enableBtIntent);
}
}
public BluetoothDevice getBTDevice(){
Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
BluetoothDevice foundDevice = null;
BTDevice = null;
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// check if the name fits the pattern K4xxx-xxxxxx
if (device.getName().matches("K4\\d\\d\\d-\\d\\d\\d\\d\\d\\d")){
foundDevice = device;
break;
}
}
if (foundDevice == null){ // if we didn't find any
Toast.makeText(context,
"ERROR: No paired BTDevice device was found, please pair a BTDevice device to continue"
, Toast.LENGTH_LONG).show();
return null;
}
}
return foundDevice; // found a BTDevice!
}
/**
* Set the current state of the chat connection
* @param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
if (D) Log.d(TAG, "setState() " + this.state + " -> " + state);
this.state = state;
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
* @param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
Log.d(TAG, "connect to: " + device.getName());
// Cancel any thread attempting to make a connection
if (connectThread != null) {connectThread.cancel(); connectThread = null;}
// Cancel any thread currently running a connection
if (connectedThread != null) {connectedThread.cancel(); connectedThread = null;}
// Start the thread to connect with the given device
connectThread = new ConnectThread(device);
connectThread.start();
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket The BluetoothSocket on which the connection was made
* @param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
Log.d(TAG, "connected to: " + device.getName());
// Cancel the thread that completed the connection
if (connectThread != null) {connectThread.cancel(); connectThread = null;}
// Cancel any thread currently running a connection
if (connectedThread != null) {connectedThread.cancel(); connectedThread = null;}
// Start the thread to manage the connection and perform transmissions
connectedThread = new ConnectedThread(socket);
connectedThread.start();
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (D) Log.d(TAG, "stop");
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
setState(STATE_NONE);
}
}
/**
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (state != STATE_CONNECTED) return;
r = connectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
private class ConnectThread extends Thread {
private final BluetoothSocket socket;
private final BluetoothDevice device;
public ConnectThread(BluetoothDevice device) {
this.device = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e(TAG, "Socket create failed", e);
}
socket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN ConnectThread");
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket.connect();
} catch (IOException e) {
// Close the socket
try {
socket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to clo开发者_JS百科se() socket during connection failure", e2);
}
return;
}
// Reset the ConnectThread because we're done
synchronized (BTCom.this) {
connectThread = null;
}
// Start the connected thread
connected(socket, this.device);
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket socket;
private final InputStream inStream;
private final OutputStream outStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
this.socket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
inStream = tmpIn;
outStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN ConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = inStream.read(buffer);
// Send the obtained bytes to the UI Activity
handler.obtainMessage(KestrelTest.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
// Start the service over to restart listening mode
break;
}
}
}
/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
outStream.write(buffer);
Log.i(TAG, "Sending " + buffer.length + " bytes");
Log.i(TAG, "Sending: " + new String(buffer));
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}
I'm stumped as to why is't not connecting... Any ideas? Thanks!
What is the device you are connecting to? Perhaps the device requires certain profiles to be supported by the host (Android) system, like A2DP, BIP, BPP etc.
The Bluetooth Chat program creates a basic client-server connection, and does not require Bluetooth Profiles support.
For Bluetooth profile support to be implemented on Android, there is a project called “Sybase-iAnywhere-Blue-SDK-for-Android”, which replaces Android's version, and provides all interfaces into the underlying Bluetooth profiles and protocols. Using this, printing over bluetooth using your Android phone will be possible using the BPP profile provided by this SDK.
See links below for more details: link 1: http://www.sybase.com/detail?id=1064424 Link 2: http://www.sybase.com/products/allproductsa-z/mobiledevicesdks/bluetoothsdks
Application profiles supported by the iAnywhere Blue SDK for Android are said to include:
Handsfree (HFP) Advanced Audio Distribution (A2DP) A/V Remote Control (AVRCP) File Transfer Protocol (FTP) Object Push Protocol (OPP) SIM Access (SAP) Phone Book Access (PBAP) Message Access Profile (MAP) Human Interface (HID) Basic Printing (BPP) Basic Imaging (BIP)
精彩评论