向远程蓝牙设备发送数据

Posted

技术标签:

【中文标题】向远程蓝牙设备发送数据【英文标题】:Sending data to remote Bluetooth device 【发布时间】:2014-02-05 02:10:11 【问题描述】:

您好,有人知道如何将数据从 android 手机发送到远程蓝牙设备(通过 OutputStream),而无需等待 InputStream 读取所需的字节数吗?

我尝试实现如下所示的代码来,但没有发送任何内容。

编辑:在 connectedThread 代码中添加:

ConnectedThread.java:

public class ConnectedThread extends Thread
        public final BluetoothSocket mmSocket;
        public final InputStream mmInStream;
        public final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket)
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            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);
                 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)  
           

public void sendData() throws IOException
            write("1");
        

ConnectThread.java:

public class ConnectThread extends Thread
        public final BluetoothSocket mmSocket;
        public final BluetoothDevice mmDevice;
        public final BluetoothAdapter mmAdapter;

        BluetoothConnection mConnectedThread = new BluetoothConnection();

        public ConnectThread(BluetoothDevice device, BluetoothAdapter mAdapter) throws SecurityException, NoSuchMethodException,  IllegalArgumentException, IllegalAccessException, InvocationTargetException 
            mmAdapter = mAdapter;
            mmDevice = device = mmAdapter.getRemoteDevice("00:06:66:4F:90:F8");
            BluetoothSocket tmp = null;

        try
            tmp = mmDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
            catch(IOException e)
                System.out.println("Failed to create Rfcomm and connect to remote device");
            
            mmSocket = tmp;
        

        public void run()
            mmAdapter.cancelDiscovery();

            //sleep to allow time for bluetooth device to get ready 
            try 
                Thread.sleep(1000);
             catch (InterruptedException e5) 
                e5.printStackTrace();
            

            //handler get message from arduino: that bluetooth device is ready 

            //Get BluetoothDevice object
            try
                //Connect to device 
                mmSocket.connect();
            try 
                Thread.sleep(1000);
             catch (InterruptedException e) 
                e.printStackTrace();
            

        catch(IOException e)
            try
                //Connect to device 
                mmSocket.connect();
            catch(IOException e1)
                
                return; 
        
            return;
        

            mConnectedThread.ConnectedThread(mmSocket);
        

    

蓝牙连接.java:

public class BluetoothConnection extends Service 

public final BluetoothAdapter mAdapter = null;
public ConnectThread mConnectThread;
    public ConnectedThread mConnectedThread;

private final IBinder mBinder = new BluetoothService();

public class BluetoothService extends Binder       
    BluetoothConnection getService()
            return BluetoothConnection.this;
    


@Override 
public IBinder onBind (Intent intent)
    Log.d("Blueooth Connection", "Intent Binder");
    return mBinder;
 

public synchronized void connect(BluetoothDevice device, BluetoothAdapter mAdapter)     throws NoSuchMethodException, IllegalAccessException, InvocationTargetException

    try
        mConnectThread = new ConnectThread(device, mAdapter);
        mConnectThread.start();

    catch(SecurityException e)
        System.out.println("SecurityException at connect()");
     catch(IllegalArgumentException e)
        System.out.println("IllegalArgumentException at connect()");
    catch(NullPointerException e)
 System.out.println("Null Pointer Exception at connect()");
    


public synchronized void ConnectedThread(BluetoothSocket socket)
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();


public void write(String out)
    //create temporary object 
    ConnectedThread r;
    synchronized(this)
        r = mConnectedThread;
               
    r.write(out);
    

@Override
public void onDestroy() 


在另一个活动中: 我打电话给 sendData();向 Arduino 写入“1”。

【问题讨论】:

您的 Android 设备名称(及其 Android 版本号)和您的蓝牙设备的确切型号名称是什么? 这很可能是兼容性问题。 Android 中的蓝牙实际上是相当碎片化的。而且它只会随着版本号的增加而改善。对不起,我没有给你答案。这个问题对我来说需要太多的研究。 请出示您的连接相关代码。 @hemerly 我已经在连接相关代码中添加了。 【参考方案1】:

编辑:

也许这不是导致您的问题的原因,但您不应该这样做:

    //Get BluetoothDevice object
    try
        //Connect to device 
        mmSocket.connect();
        try 
            Thread.sleep(1000);
         catch (InterruptedException e) 
            e.printStackTrace();
        

    catch(IOException e)
        try
            //Connect to device 
            mmSocket.connect();
        catch(IOException e1)
        
        return; 
    

您可能以未连接的mmSocket 结束,因为您只是忽略了IOException 并重试。在第一个 try/catch 块中尝试e.printStackTrace(),看看您是否有连接问题。

一般来说,您永远不应该忽略异常,因为它们代表程序流程中的异常。在最坏的情况下,打印一条错误消息以帮助您进行调试。

编辑 2:

请更改

public void write(byte[] bytes) 
    try 
        mmOutStream.write(bytes);
     catch (IOException e)  
   

public void write(byte[] bytes) 
    try 
        mmOutStream.write(bytes);
     catch (IOException e)  
        e.printStackTrace();
    
   

并查看 logcat 输出,看看它是否显示有问题。

【讨论】:

试过了,还是不行。通过将服务绑定到活动,连接保持活动状态。 感谢您的建议!但是,我设法在手机和远程蓝牙设备之间建立连接,但无法通过 write() 向设备发送任何内容。程序卡在 while(true) 循环中。 您好,我在 e.printStackTrace();但没有打印任何内容。 write() 根本没有被调用。

以上是关于向远程蓝牙设备发送数据的主要内容,如果未能解决你的问题,请参考以下文章

蓝牙 GATT 向 BLE 设备发送数据

通过写入 DataOutputStream 通过蓝牙向设备发送命令

使用蓝牙将文件发送到远程设备,而无需使用终端中的obexftp引脚

IOS蓝牙设备数据回调的坑

向配对的蓝牙设备发送 int

向核心蓝牙框架 Xcode 发送数据