How to send and receive data in Android Programming using bluetooth without pairing?

前端 未结 2 1657
轻奢々
轻奢々 2020-12-16 08:53

I am new to Android programming, and have java concept, I want to know that how can I send and receive data using bluetooth without pairing or any password (Only if both dev

2条回答
  •  误落风尘
    2020-12-16 08:54

    I got the the following from this Google groups post by Kristopher Micinski. Hope it helps.

    I believe the key to getting this to work is in the mUuid list.

    Take a close look at what this is doing:

    for (int i = 0; i < Connection.MAX_SUPPORTED && myBSock == null; i++) {
        for (int j = 0; j < 3 && myBSock == null; j++) {
            myBSock = getConnectedSocket(myBtServer, mUuid.get(i));
            if (myBSock == null) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    Log.e(TAG, "InterruptedException in connect", e);
                }
            }
        }
    }
    


    What this code does is looks to connect to the device, but how does it do so? It tries the socket multiple times, using multiple UUIDs for the session.

    In essence it means that we can use UUID only once. So instead this application implements using seven UUIDs, then the server listens and accepts each UUID on the server side, this is what is done with the following code:

    for (int i = 0; i < Connection.MAX_SUPPORTED && maxConnections > 0; i++) {
        BluetoothServerSocket myServerSocket = mBtAdapter.listenUsingRfcommWithServiceRecord(srcApp, mUuid.get(i));
        BluetoothSocket myBSock = myServerSocket.accept();
        myServerSocket.close(); // Close the socket now that the
        // connection has been made.
    
        String address = myBSock.getRemoteDevice().getAddress();
    
        mBtSockets.put(address, myBSock);
        mBtDeviceAddresses.add(address);
        Thread mBtStreamWatcherThread = new Thread(new BtStreamWatcher(address));
        mBtStreamWatcherThread.start();
        mBtStreamWatcherThreads.put(address, mBtStreamWatcherThread);
        maxConnections = maxConnections - 1;
        if (mCallback != null) {
            mCallback.incomingConnection(address);
        }
    }
    

    Now, on the client side of things what is done? The client does not know how many active connections the server currently has.

    If we have some agreed upon order that the clients must use we can simply use this, however, in our case, we simply just try each UUID in sequence until we "find the right one."

    Short version: -- Use multiple UUIDs, you can only use one at once. So define seven (max for piconet usage) and try each one until you find the right one.

提交回复
热议问题