简体   繁体   English

Android与串口设备的蓝牙连接

[英]Android Bluetooth connection with Serial Port Device

I have used BluetoothChatService class from BluetoothChat example program for bluetooth connection. 我已经使用BluetoothChat示例程序中的BluetoothChatService类进行了蓝牙连接。 I have modified it like 我已经修改了

private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 私有静态最终UUID MY_UUID = UUID.fromString(“ 00001101-0000-1000-8000-00805F9B34FB”);

to connect it to a Serial Port Device. 将其连接到串行端口设备。

My sample test android devices are NexusOne, HTC Desire, LG Optimus, Motorola Droid. 我的示例测试android设备是NexusOne,HTC Desire,LG Optimus和Motorola Droid。

Whenever I use my application to connect it to a Hardware it connects and disconnects appropriately using NexusOne. 每当我使用我的应用程序将其连接到硬件时,它都会使用NexusOne进行适当的连接和断开连接。 But when using other android devices sometime they connect , sometimes even after trying 100s of times it doesn't connect. 但是,有时在使用其他android设备时会连接,有时甚至尝试100次后仍无法连接。 And sometimes when i disconnect , the application disconnects but the bluetooth light on the hardware is ON, indicating the connection is still ON . 有时,当我断开连接时,应用程序断开连接,但硬件上的蓝牙指示灯亮起,表明连接仍为ON。 I am wondering if its my coding error, or hardware error, or Android OS bluetooth library error. 我想知道它是我的编码错误,硬件错误还是Android OS蓝牙库错误。 I haven't face this issue with NexusOne. NexusOne尚未解决此问题。 I haven't been able to pinpoint the exact location as to where the issue lies. 我无法查明问题所在的确切位置。

Can someone point me what could be the possible course of action I should take to solve this issue ? 有人可以指出我应该采取什么行动来解决这个问题吗?


Code that gives "Unable to connect device" Toast Message 给出“无法连接设备” Toast消息的代码

/** / **

 * Constructor. Prepares a new BluetoothChat session.

 * @param context  The UI Activity Context

 * @param handler  A Handler to send messages back to the UI Activity

 */


public BluetoothChatService(Context context, Handler handler) {
    mAdapter = BluetoothAdapter.getDefaultAdapter();
    mState = STATE_NONE;
    mHandler = handler;
}

/**
 * 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() " + mState + " -> " + state);
    mState = state;

    // Give the new state to the Handler so the UI Activity can update
    mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}

/**
 * Return the current connection state. */
public synchronized int getState() {
    return mState;
}

/**
 * Start the chat service. Specifically start AcceptThread to begin a
 * session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
    if (D) Log.d(TAG, "start");

    // Cancel any thread attempting to make a connection
    if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

    setState(STATE_LISTEN);

    // Start the thread to listen on a BluetoothServerSocket
    if (mSecureAcceptThread == null) {
        mSecureAcceptThread = new AcceptThread(true);
        mSecureAcceptThread.start();
    }
    if (mInsecureAcceptThread == null) {
        mInsecureAcceptThread = new AcceptThread(false);
        mInsecureAcceptThread.start();
    }
}

/**
 * Start the ConnectThread to initiate a connection to a remote device.
 * @param device  The BluetoothDevice to connect
 * @param secure Socket Security type - Secure (true) , Insecure (false)
 */
public synchronized void connect(BluetoothDevice device, boolean secure) {
    if (D) Log.d(TAG, "connect to: " + device);

    // Cancel any thread attempting to make a connection
    if (mState == STATE_CONNECTING) {
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
    }

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

    // Start the thread to connect with the given device
    mConnectThread = new ConnectThread(device, secure);
    mConnectThread.start();
    setState(STATE_CONNECTING);
}

/**
 * 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, final String socketType) {
    if (D) Log.d(TAG, "connected, Socket Type:" + socketType);

    // Cancel the thread that completed the connection
    if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

    // Cancel the accept thread because we only want to connect to one device
    if (mSecureAcceptThread != null) {
        mSecureAcceptThread.cancel();
        mSecureAcceptThread = null;
    }
    if (mInsecureAcceptThread != null) {
        mInsecureAcceptThread.cancel();
        mInsecureAcceptThread = null;
    }

    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket, socketType);
    mConnectedThread.start();

    // Send the name of the connected device back to the UI Activity
    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
    msg.setData(bundle);
    mHandler.sendMessage(msg);

    setState(STATE_CONNECTED);
}

/**
 * Stop all threads
 */
public synchronized void stop() {
    if (D) Log.d(TAG, "stop");

    if (mConnectThread != null) {
        mConnectThread.cancel();
        mConnectThread = null;
    }

    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }

    if (mSecureAcceptThread != null) {
        mSecureAcceptThread.cancel();
        mSecureAcceptThread = null;
    }

    if (mInsecureAcceptThread != null) {
        mInsecureAcceptThread.cancel();
        mInsecureAcceptThread = 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 (mState != STATE_CONNECTED) return;
        r = mConnectedThread;
    }
    // Perform the write unsynchronized
    r.write(out);
}

/**
 * Indicate that the connection attempt failed and notify the UI Activity.
 */
private void connectionFailed() {
    // Send a failure message back to the Activity
    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.TOAST, "Unable to connect device");
    msg.setData(bundle);
    mHandler.sendMessage(msg);

    // Start the service over to restart listening mode
    BluetoothChatService.this.start();
}

/**
 * Indicate that the connection was lost and notify the UI Activity.
 */
private void connectionLost() {
    // Send a failure message back to the Activity
    Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
    Bundle bundle = new Bundle();
    bundle.putString(BluetoothChat.TOAST, "Device connection was lost");
    msg.setData(bundle);
    mHandler.sendMessage(msg);

    // Start the service over to restart listening mode
    BluetoothChatService.this.start();
}

Does the UUID used for the server code written for the "custom made hardware", match with the UUID used on the Android phone? 用于为“定制硬件”编写的服务器代码的UUID是否与Android手机上使用的UUID匹配? It maybe that the Nexus One may be the only phone (among your phones) that uses Gingerbread (?) and that would mean a higher API level, than previous versions of Android. Nexus One可能是您手机中唯一使用Gingerbread(?)的手机,并且这意味着比以前的Android版本更高的API级别。 Go through the change logs of Gingerbread relating to Bluetooth. 浏览与蓝牙有关的Gingerbread更改日志。 That would probably be the reason. 那可能就是原因。

Well the code had some errors ... they were solved once i went over the Activity's complete lifecycle and implemented according to that. 好吧,代码中有一些错误……一旦我完成了Activity的整个生命周期并据此实施,就可以解决它们。 The class given is fine. 给的班很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM