首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法连接蓝牙设备

无法连接蓝牙设备
EN

Stack Overflow用户
提问于 2014-09-13 08:21:16
回答 2查看 1.9K关注 0票数 1

我试图连接蓝牙设备,希望将数据发送到该设备,同时也希望从该设备接收数据。

为了实现这一点,我遵循android开发者蓝牙文档,但似乎无法连接另一个设备,因为连接时它会抛出以下异常。

代码语言:javascript
复制
09-13 13:27:56.913: I/BluetoothConnect(2980): Connect exception:-java.io.IOException: [JSR82] connect: Connection is not created (failed or aborted).    

我遵循的步骤.

  1. 启用蓝牙 意图turnOnIntent =新意图( BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(turnOnIntent,REQUEST_ENABLE_BT);
  2. 获取蓝牙配对DeviceSet bondSet = myBluetoothAdapter.getBondedDevices();ArrayList> bondedhDevicesList =新ArrayList>();for (Iterator it = bondSet.iterator();it.hasNext();) { BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next();HashMap map = new HashMap();HashMap
  3. 获取devicebluetoothDevice =myBluetoothAdapter.getRemoteDevice(地址)的UUID;// min 15!方法m;尝试{m= bluetoothDevice.getClass()。getMethod("fetchUuidsWithSdp",(Class[]) null);m.invoke(bluetoothDevice,(Object[]) null );} catch (NoSuchMethodException IllegalAccessException IllegalArgumentException InvocationTargetException e) { // TODO自动生成的catch e.printStackTrace()};
  4. 连接到设备

代码语言:javascript
复制
   private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");

    public ConnectThread(BluetoothDevice device, String uuid, BluetoothAdapter mBluetoothAdapter) {
    // Use a temporary object that is later assigned to mmSocket,
    // because mmSocket is final
    BluetoothSocket tmp = null;
    this.mBluetoothAdapter = mBluetoothAdapter;
    mmDevice = device;

    Method m;
    try {
        mBluetoothAdapter.cancelDiscovery();
        mmSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
        m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
        mmSocket = (BluetoothSocket) m.invoke(device, 1);   
    } catch (IOException |  IllegalArgumentException | IllegalAccessException | InvocationTargetException | NoSuchMethodException  e) {
        // TODO Auto-generated catch block
        Log.i("BluetoothConnect", e.toString());
        e.printStackTrace();
     }

     //mBluetoothAdapter.cancelDiscovery();
     //socket.connect();
    } 
    public void run() {
    // Cancel discovery because it will slow down the connection
    mBluetoothAdapter.cancelDiscovery(); 
    try {
        // Connect the device through the socket. This will block
        // until it succeeds or throws an exception
        mmSocket.connect();
        Constants.globalSocket = mmSocket;
    } catch (IOException connectException) {
        // Unable to connect; close the socket and get out
        Log.i("BluetoothConnect", "Connect exception:-"+connectException.toString());
        try {
            mmSocket.close();
        } catch (IOException closeException) { 
            Log.i("BluetoothConnect", "close exception:-"+closeException.toString());
        }
        return;
    }         
}

但是在连接的时候,我得到了这个例外。

  1. 写到设备上。
代码语言:javascript
复制
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 = 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
            CreatePacket.mHandler.obtainMessage(MESSAGE_READ , bytes, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.i("ConnectedThread", "while receiving data:-"+e.toString());
            break;
        }
      }
     }       


  public void write(byte[] bytes) {
    Log.i("ConnectedThread", "data while writing:-"+bytes.toString());
    try {
        mmOutStream.write(bytes);
    } catch (IOException e) {
        Log.i("ConnectedThread", "while writing data to bluetooth:-"+e.toString());
    }
  }    

如果我仍然尝试编写数据,那么我将得到以下异常。

请给我任何提示或参考。

代码语言:javascript
复制
09-13 13:48:55.079: I/ConnectedThread(2980): while writing data to bluetooth:-java.io.IOException: socket closed

我被困在过去三天,但仍然没有得到任何解决办法。

EN

回答 2

Stack Overflow用户

发布于 2014-09-15 06:43:22

最好的方法是引用Android提供的示例聊天应用程序。这涵盖了所有必要的任务,如列出可用的设备,建立连接,发送数据和接收等。你可以得到和参考。https://android.googlesource.com/platform/development/+/eclair-passion-release/samples/BluetoothChat

票数 1
EN

Stack Overflow用户

发布于 2015-02-07 05:32:58

下面是我用来连接蓝牙模块的一个示例代码。

代码语言:javascript
复制
public class OpenBluetoothPort extends AsyncTask<String, Void, BluetoothSocket> {

    private final UUID SPP_UUID = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB");
    private BluetoothAdapter mBluetoothAdapter;
    private OnBluetoothPortOpened mCallback;
    private BluetoothSocket mBSocket;

    public interface OnBluetoothPortOpened {
        public void OnBluetoothConnectionSuccess(BluetoothSocket socket);
        public void OnBluetoothConnectionFailed();
    }

    public OpenBluetoothPort(Context context, OnBluetoothPortOpened callback) {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mCallback = callback;
    }

    @Override
    protected BluetoothSocket doInBackground(String... params) {
        if(mBluetoothAdapter.isEnabled()) {
            try {
                for(BluetoothDevice bt: mBluetoothAdapter.getBondedDevices()) {
                    if(bt.getName().equalsIgnoreCase(params[0])) {
                        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(bt.getAddress());
                        mBluetoothAdapter.cancelDiscovery();

                        mBSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
                        mBSocket.connect();
                        return mBSocket;
                    }
                }
            } catch(IOException e) {
                if(mBSocket != null) {
                    try {
                        mBSocket.close();
                    } catch (IOException e1) {
                        Log.i("Bluetooth Close Exception","Error in closing bluetooth in OpenBluetoothPort.class");
                        e1.printStackTrace();
                    }
                    mBSocket = null;
                }
                Log.i("Bluetooth Connect Exception","Error in connecting in OpenBluetoothPort.class");
                e.printStackTrace();
                return null;
            }
        } 
        return null;
    }

    @Override
    protected void onPostExecute(BluetoothSocket result) {
        super.onPostExecute(result);
        if(result != null && result.isConnected()) {
            mCallback.OnBluetoothConnectionSuccess(result);
        } else {
            mCallback.OnBluetoothConnectionFailed();
        }
    }



}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25821267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档