简体   繁体   English

无法连接蓝牙设备

[英]unable to connect bluetooth device

I am trying to connect bluetooth device and want to send data to that device and also want to receive data from that device. 我正在尝试连接蓝牙设备,并希望将数据发送到该设备,并且还希望从该设备接收数据。

To achieve this I follow android developer bluetooth document but seems I unable to connect another device because while connecting it's throwing following exception. 为此,我遵循android开发人员蓝牙文档,但似乎无法连接其他设备,因为连接时会引发以下异常。

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

Steps which I follow. 我遵循的步骤。

  1. Enabling Bluetooth 启用蓝牙

     Intent turnOnIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT); 
  2. Getting Bluetooth Paired Device 获取蓝牙配对设备

     Set<BluetoothDevice> bondSet = myBluetoothAdapter.getBondedDevices(); ArrayList<HashMap<String, String>> bondedhDevicesList = new ArrayList<HashMap<String, String>>(); for (Iterator<BluetoothDevice> it = bondSet.iterator(); it.hasNext();) { BluetoothDevice bluetoothDevice = (BluetoothDevice) it.next(); HashMap<String, String> map = new HashMap<String, String>(); map.put("name", bluetoothDevice.getName()); map.put("address", bluetoothDevice.getAddress()); bondedhDevicesList.add(map); } 
  3. Getting UUID of device 获取设备的UUID

      bluetoothDevice = myBluetoothAdapter.getRemoteDevice(address); // min api 15 !!! Method m; try { m = bluetoothDevice.getClass(). getMethod("fetchUuidsWithSdp", (Class[]) null); m.invoke(bluetoothDevice, (Object[]) null ); } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } 
  4. Connecting to device 连接到设备

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

But while connecting then i am getting that exception. 但是,在连接时,我得到了那个例外。
5. Writing to device. 5.写入设备。

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

If I still try to write then data then I am getting following exception. 如果我仍然尝试写入数据,那么我将遇到以下异常。

Please give me any hint or reference. 请给我任何提示或参考。

09-13 13:48:55.079: I/ConnectedThread(2980): while writing data to bluetooth:-java.io.IOException: socket closed

I am stuck on this from last three day but still not getting any solution. 从最近三天开始,我就一直坚持这一点,但仍然没有任何解决方案。

The best way is to refer the sample chat application provided by the Android. 最好的方法是引用Android提供的示例聊天应用程序。 That has covered all necessary tasks like list out available devices, establish connection, send data and receive, etc. U can get that and refer. 这涵盖了所有必要的任务,例如列出可用设备,建立连接,发送数据和接收等。U可以获取并引用。 https://android.googlesource.com/platform/development/+/eclair-passion-release/samples/BluetoothChat https://android.googlesource.com/platform/development/+/eclair-passion-release/samples/BluetoothChat

Here is a sample code which I am using to connect to my Bluetooth module.. 这是我用于连接到蓝牙模块的示例代码。

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



}

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

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