NullPointer Exception on socket.connect() Galaxy Tab 2 running Android 4.04

后端 未结 2 712
隐瞒了意图╮
隐瞒了意图╮ 2021-01-03 10:02

I seem to be facing this weird error on a socket.connect():

09-18 14:41:22.968: W/System.err(2593): java.lang.NullPointerException
09-18 14:41:22.968: W/Syst         


        
相关标签:
2条回答
  • 2021-01-03 10:20

    I had the same problem with the Galaxy tab 2 and I solved with:

            BluetoothSocket tmp = null;
            try {
                tmp = device.createRfcommSocketToServiceRecord(SPP_UUID);
    
                // for others devices its works with:
                // Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
    
                // for galaxy tab 2 with:
                Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
    
                tmp = (BluetoothSocket) m.invoke(device, 1);
            } catch (IOException e) {
                Log.e(TAG, "failed! error: " + e.getMessage());
            }
            socket = tmp;
    
            socket.connect();
            Log.i(TAG, "Client Connected!");
    

    Hope this helps =D

    0 讨论(0)
  • 2021-01-03 10:24

    Warning: the code below may be insecure, use at your own risk

    In my case I was able to connect using createInsecureRfcommSocketToServiceRecord rather than createRfcommSocketToServiceRecord but I see you were already doing that. My code looks more like this (error/exception checking removed):

    BluetoothDevice device;
    String deviceName = ... selected or hardcoded device name. See Android HDR sample code
    BluetoothDevice[] mAllBondedDevices = (BluetoothDevice[]) mBluetoothAdapter.getBondedDevices().toArray(new BluetoothDevice[0]);
    
    for (BluetoothDevice d : mAllBondedDevices) {
      if (deviceName.equals(d.getName())) {
        device = d;
        break;
      }
    }
    
    UUID uuid = device.getUuids()[0].getUuid();
    //FAILED: socket = device.createRfcommSocketToServiceRecord(uuid);
    // Succeeds: Warning, INSECURE!
    socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
    socket.connect();
    this.dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    this.dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    //etc 
    

    Note that while an insecure connection is not perfect, in our case an insecure connection is preferable to no connection. I posted this an an answer so that you could try the alternate code.

    0 讨论(0)
提交回复
热议问题