Исключение NullPointer для socket.connect() Galaxy Tab 2 под управлением Android 4.04

Я, кажется, сталкиваюсь с этой странной ошибкой в ​​socket.connect():

09-18 14:41:22.968: W/System.err(2593): java.lang.NullPointerException
09-18 14:41:22.968: W/System.err(2593):     at android.sec.enterprise.BluetoothUtils.**isSocketAllowedBySecurityPolicy**(BluetoothUtils.java:106)
09-18 14:41:22.968: W/System.err(2593):     at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:220)
09-18 14:41:22.968: W/System.err(2593):     at com._._.android._._.bluetoothmodule.BluetoothController.connectToDevice(BluetoothController.java:136)
09-18 14:41:22.976: W/System.err(2593):     at com._._.android._._.controllermodule.ControllerModule.connectToDevice(ControllerModule.java:235)
09-18 14:41:22.976: W/System.err(2593):     at com._._.android._._.controllermodule.ControllerModule.connectToDevice(ControllerModule.java:263)
09-18 14:41:22.976: W/System.err(2593):     at com._._.android._._.service.ConnectionService.onHandleIntent(ConnectionService.java:70)
09-18 14:41:22.976: W/System.err(2593):     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
09-18 14:41:22.976: W/System.err(2593):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-18 14:41:22.976: W/System.err(2593):     at android.os.Looper.loop(Looper.java:137)
09-18 14:41:22.976: W/System.err(2593):     at android.os.HandlerThread.run(HandlerThread.java:60)

Да, я проверяю, является ли сокет нулевым, прежде чем подключаться к нему. Я, кажется, сталкиваюсь только с этой проблемой на Galaxy Tab 2 под управлением 4.0.4. Мой код прекрасно работает на других устройствах / версиях Android [в том числе JB]. Не уверен, что здесь может происходить. Ниже приведен небольшой фрагмент, демонстрирующий, как я инициализирую свой сокет:

Method m = bluetoothDevice.getClass().getMethod(
            "createInsecureRfcommSocket", new Class[] { int.class });
Logging.getInstance().logMessage(this.getClass().getSimpleName(), "Returned the Reflection method successfully..",Logging.LOG_ERROR);
      // get readSocket
    mreadSocket = (BluetoothSocket) m.invoke(bluetoothDevice, 1);
      assert (mreadSocket != null) : "readSocket is Null";
 if (mreadSocket != null) {

        mreadSocket.connect();
}

Любая помощь будет принята с благодарностью!

2 ответа

Решение

Предупреждение: приведенный ниже код может быть небезопасным, используйте на свой страх и риск

В моем случае я смог подключиться с помощью createInsecureRfcommSocketToServiceRecord скорее, чем createRfcommSocketToServiceRecord но я вижу, ты уже делал это. Мой код выглядит примерно так (проверка ошибок / исключений удалена):

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 

Обратите внимание, что хотя небезопасное соединение не является совершенным, в нашем случае небезопасное соединение предпочтительнее отсутствия соединения. Я разместил ответ, чтобы вы могли попробовать альтернативный код.

У меня была та же проблема с Galaxy Tab 2, и я решил с помощью:

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

Надеюсь, это поможет =D

Другие вопросы по тегам