管理蓝牙连接Android

时间:2014-02-19 01:17:51

标签: android bluetooth arduino android-bluetooth

我目前正在尝试将蓝牙HC-05模块与Android连接,以便通过模块将字节发送到Android设备。我几乎直接从android开发者页面抢了一些代码: http://developer.android.com/guide/topics/connectivity/bluetooth.html#ManagingAConnection

这是Main。我遇到的问题是mhandler没有收到MESSAGE_READ的情况,这意味着我没有从我的模块接收数据。我想知道我需要做些什么来发送数据来运行MESSAGE_READ案例?到目前为止,程序将设备配对并将“成功连接”发送到我的arduino。

这也是一个先前被问过的问题,有人可能比我更好,但没有回答,所以我想我不是唯一的问题。

https://stackoverflow.com/questions/20088856/no-data-buffered-from-bluetooth-module

我在代码中看到的差异主要是他确实启动了()他的connectedThread()。谢谢你的帮助!

public class Main_Activity extends Activity implements OnItemClickListener {

ArrayAdapter<String> listAdapter;

ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        Log.i(tag, "in handler");
        super.handleMessage(msg);
        switch(msg.what){
        case SUCCESS_CONNECT:
            // DO something
            ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
            //Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
            String s = "successfully connected";
            connectedThread.write(s.getBytes());                
            Log.i(tag, "connected");

            break;
        case MESSAGE_READ:
            byte[] readBuf = (byte[])msg.obj;
            String string = new String(readBuf);
            Toast.makeText(getApplicationContext(), string, 0).show();              
            break;  

        }
    }

};

以下是应该发送处理程序的代码:

private class ConnectThread extends Thread {

        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            // Use a temporary object that is later assigned to mmSocket,
            // because mmSocket is final
            BluetoothSocket tmp = null;
            mmDevice = device;
            Log.i(tag, "construct");
            // 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(MY_UUID);
            } catch (IOException e) { 
                Log.i(tag, "get socket failed");

            }
            mmSocket = tmp;
        }

        public void run() {
            // Cancel discovery because it will slow down the connection
            btAdapter.cancelDiscovery();
            Log.i(tag, "connect - run");
            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
                Log.i(tag, "connect - succeeded");
            } catch (IOException connectException) {    Log.i(tag, "connect failed");
                // 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)

            mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
        }



        /** Will cancel an in-progress connection, and close the socket */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }

    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;  // 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
                    buffer = new byte[1024];
                    bytes = mmInStream.read(buffer);
                    // Send the obtained bytes to the UI activity
                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();

                } catch (IOException e) {
                    break;
                }
            }
        }

3 个答案:

答案 0 :(得分:1)

你使用线程是完全错误的。

创建线程对象不会启动物理线程!

因此,正如您所做的那样,放置一个可能很慢的套接字创建函数 线程对象的构造函数再次出错。

而且,既然你没有启动() - 你的线程,socket connect()永远不会被调用!

请尝试以下几点:

class ConnectThread extends Thread {

     public ConnectThread(BluetoothDevice device) {
            // nothing long running here!
     }

     public void run() {
         device.createRfcommSocketToServiceRecord(MY_UUID);

         // followed by connect() etc.
     }
}

请记住通过调用

来激活线程
  connectedThread.start();

否则什么也不会发生。

答案 1 :(得分:0)

我记得处理程序有类似的问题。很久以前,所以我不记得每一个细节,但它与mHandler.sendToTarget有关。我认为有一个mHandler.dispatchMessage方法(或者像这样 - 我不在我的编程电脑上,所以我现在无法验证这一点)。 你应该试一试。

答案 2 :(得分:0)

你确定“成功连接”字符串确实收到了arduino吗?代码片段没有显示连接线程的写入方法。请参阅android sdk中提供的bluetoothchat源代码。

您可以寻找几个方面:

1)在连接线程开始之前,连接线程未关闭。

2)常量的定义SUCCESS_CONNECT&amp; MESSAGE_READ。它们是私有的,但可以从不同的类访问。在bluetoothchat源中,它们被定义为公共。

此外,在从不同的类中引用这些常量时,我​​们需要引用它们所定义的类,即如下所示引用它们:

Main_Activity.SUCCESS_CONNECT 
Main_Activity.MESSAGE_READ.