android - 蓝牙问题 : myUserId = 0

标签 android bluetooth

当我尝试连接到蓝牙时,我收到以下消息,仅在我的 samsung galaxy s7 上:

I/BT: Attempting to connect to Protocol: 00001105-0000-1000-8000-00805f9b34fb
D/BluetoothAdapter: cancelDiscovery
D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
D/BluetoothSocket: connect(): myUserId = 0
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
D/BluetoothSocket: getInputStream(): myUserId = 0
D/BluetoothSocket: getOutputStream(): myUserId = 0

在我的 nexus 5x 上使用完全相同的代码不会向我发送“myUserId = 0”。

似乎这个“问题”阻止了我的应用程序和其他设备之间的通信。

这是我的代码:

private class btSend extends AsyncTask<Void, Void, Void>{

        @Override
        protected void onPreExecute(){
            Log.i("BT Connection", "Establishing connection...");

        }

        @Override
        protected Void doInBackground(Void... devices) {

            List<UUID> list = new ArrayList<>();

            for (ParcelUuid id : bluetoothDevice.getUuids()) {
                list.add(id.getUuid());
            }

            BluetoothSocketConnector bluetoothSocketConnector = new BluetoothSocketConnector(bluetoothDevice, false, bluetoothAdapter, list);
            try {
                bluetoothSocket = bluetoothSocketConnector.connect();

                inputStream = bluetoothSocket.getInputStream();
                outputStream = bluetoothSocket.getOutputStream();

                btConnectSuccess = true;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            super.onPostExecute(result);

            if(btConnectSuccess) {
                while(true){
                    try {
                        sleep(5000);
                        sendData();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


    }

发送数据:

void sendData() throws IOException
    {
        String msg = "Test message\r\n";
        if (msg!=null) {
            byte[] msgBuffer = msg.getBytes();
            try {
                outputStream.write(msgBuffer);
                Log.w("Bluetooth", "Data sent"+msgBuffer);
            } catch (IOException e) {
                Log.e("BT send error", e.getMessage(), e);
            }
        }
    }

蓝牙套接字连接器:

public class BluetoothSocketConnector {

    private BluetoothSocketWrapper bluetoothSocket;
    private BluetoothDevice device;
    private boolean secure;
    private BluetoothAdapter adapter;
    private List<UUID> uuidCandidates;
    private int candidate;


    /**
     * @param device the device
     * @param secure if connection should be done via a secure socket
     * @param adapter the Android BT adapter
     * @param uuidCandidates a list of UUIDs. if null or empty, the Serial PP id is used
     */
    public BluetoothSocketConnector(BluetoothDevice device, boolean secure, BluetoothAdapter adapter,
                                    List<UUID> uuidCandidates) {
        this.device = device;
        this.secure = secure;
        this.adapter = adapter;
        this.uuidCandidates = uuidCandidates;

        if (this.uuidCandidates == null || this.uuidCandidates.isEmpty()) {
            this.uuidCandidates = new ArrayList<UUID>();
            this.uuidCandidates.add(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
        }
    }

    public BluetoothSocketWrapper connect() throws IOException {
        boolean success = false;
        while (selectSocket()) {
            adapter.cancelDiscovery();

            try {
                bluetoothSocket.connect();
                success = true;
                break;
            } catch (IOException e) {
                //try the fallback
                try {
                    bluetoothSocket = new FallbackBluetoothSocket(bluetoothSocket.getUnderlyingSocket());
                    Thread.sleep(500);
                    bluetoothSocket.connect();
                    success = true;
                    break;
                } catch (FallbackException e1) {
                    Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
                } catch (InterruptedException e1) {
                    Log.w("BT", e1.getMessage(), e1);
                } catch (IOException e1) {
                    Log.w("BT", "Fallback failed. Cancelling.", e1);
                }
            }
        }

        if (!success) {
            throw new IOException("Could not connect to device: "+ device.getAddress());
        }

        return bluetoothSocket;
    }

    private boolean selectSocket() throws IOException {
        if (candidate >= uuidCandidates.size()) {
            return false;
        }

        BluetoothSocket tmp;
        UUID uuid = uuidCandidates.get(candidate++);

        Log.i("BT", "Attempting to connect to Protocol: "+ uuid);
        if (secure) {
            tmp = device.createRfcommSocketToServiceRecord(uuid);
        } else {
            tmp = device.createInsecureRfcommSocketToServiceRecord(uuid);
        }
        bluetoothSocket = new NativeBluetoothSocket(tmp);

        return true;
    }

    public static interface BluetoothSocketWrapper {

        InputStream getInputStream() throws IOException;

        OutputStream getOutputStream() throws IOException;

        String getRemoteDeviceName();

        void connect() throws IOException;

        String getRemoteDeviceAddress();

        void close() throws IOException;

        BluetoothSocket getUnderlyingSocket();

    }


    public static class NativeBluetoothSocket implements BluetoothSocketWrapper {

        private BluetoothSocket socket;

        public NativeBluetoothSocket(BluetoothSocket tmp) {
            this.socket = tmp;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return socket.getInputStream();
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            return socket.getOutputStream();
        }

        @Override
        public String getRemoteDeviceName() {
            return socket.getRemoteDevice().getName();
        }

        @Override
        public void connect() throws IOException {
            socket.connect();
        }

        @Override
        public String getRemoteDeviceAddress() {
            return socket.getRemoteDevice().getAddress();
        }

        @Override
        public void close() throws IOException {
            socket.close();
        }

        @Override
        public BluetoothSocket getUnderlyingSocket() {
            return socket;
        }

    }

    public class FallbackBluetoothSocket extends NativeBluetoothSocket {

        private BluetoothSocket fallbackSocket;

        public FallbackBluetoothSocket(BluetoothSocket tmp) throws FallbackException {
            super(tmp);
            try
            {
                Class<?> clazz = tmp.getRemoteDevice().getClass();
                Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
                Method m = clazz.getMethod("createRfcommSocket", paramTypes);
                Object[] params = new Object[] {Integer.valueOf(1)};
                fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
            }
            catch (Exception e)
            {
                throw new FallbackException(e);
            }
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return fallbackSocket.getInputStream();
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            return fallbackSocket.getOutputStream();
        }


        @Override
        public void connect() throws IOException {
            fallbackSocket.connect();
        }


        @Override
        public void close() throws IOException {
            fallbackSocket.close();
        }

    }

    public static class FallbackException extends Exception {

        /**
         *
         */
        private static final long serialVersionUID = 1L;

        public FallbackException(Exception e) {
            super(e);
        }

    }
}

最佳答案

好吧,在另一个项目上工作了几天后,我得到了答案...事实上,“myUserId=0”不是问题所在——监听器卡在了我应用程序中其他地方的循环中。

似乎此日志消息不会影响行为 - 我已经检查了官方 Android 蓝牙演示,它返回了相同的消息但运行良好。

关于android - 蓝牙问题 : myUserId = 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47468093/

相关文章:

Android Canvas 使用位图撤消和重做

Android Mosquitto - 客户端连接状态

安卓蓝牙 : Add service data without UUID

c# - Xamarin.iOS 上的蓝牙请求权限

python - 如何从 Mac 连接到蓝牙 4.0/蓝牙 LE 设备?

android - 如何使用Achartengine实现折线图

android.provider.CallLog.Calls.TYPE 拨出电话未接听且拨出电话被拒绝?

android - 卢比符号未在 android 中显示

android - 有没有办法在我的 Android 应用程序中暂停(或静音)默认音乐播放器?

java - 我如何在一秒内实时获得蓝牙 RSSI 10 次,持续 10 秒