Android Bluetooth

classic bluetooth and bluetooth low energy (BLE)

APIs
1.scan for other bluetooth devices,include BLE
2.Query the local bluetoth adapter for paired bluetooth devices
3.establish RFCOMM channels/sockets
4.connect to specified sockets on other devices
5.transfer data to and from other devices
6.communicate with BLE devices, such as proximity sensors,heart rate monitors,fitness devices,and so on
7.(BLE)act as a GATT client or a GATT server

permission
android.permission.BLUETOOTH
allows apps to connect to paired bluetooth devices ,normal level

android.permission.BLUETOOTH_ADMIN
allows apps to discover and pair bluetooth devices,normal level

android.permission.BLUETOOTH_PRIVILEGED
allows apps to pair blurtooth devices without use interaction ,and to allow or disallow phonebook access or message access,not for use by third-party apps

extras
BluetoothProfile.EXTRA_STATE (the current state of the profile)
BluetoothProfile.EXTRA_PERVIOUS_STATE (the previos state of the profile )
BluetoothDevice#EXTRA_DEVICE (the remote device,not state )

broadcast

ACTION_CONNECTION_STATE_CHANGED
intent used to broadcast the change in connection state of A2DP profile
A2DP:Advanced Audio Distribution Profile

bluetooth state (BluetoothProfile.EXTRA_STATE,BluetoothProfile.EXTRA_PERVIOUS_STATE)
BluetoothProfile.STATE_DISCONNECTED
BluetoothProfile.STATE_DISCONNECTING
BluetoothProfile.STATE_CONNECTING
BluetoothProfile.STATE_CONNECTED

ACTION_PLAYING_STATE_CHANGED
intent used to broadcast the change in the playing state of the A2DP profile

bluetooth state (BluetoothProfile.EXTRA_STATE,BluetoothProfile.EXTRA_PERVIOUS_STATE,ACTION_CONNECTION_STATE_CHANGED)
STATE_PLAYING (is streaming music)
STATE_NOT_PLAYING (is not stream music)

public methods
void finalize();
gc

BlurtoothA2DP providers the public APIs to control the bluetooth A2DP profile

List getConnectedDevices()
return the set of devices which are in state STATE_CONNECTED

int getConnectionState(BludetoothDevice device)
get the currention state of the profile

List getDevicesMatchingConnectionStates(int[] state)
get a list of devices that match any of the given connection state

boolean isA2dpPlaying(BluetoothDevice device)
check id A2DP profile is streaming music

BluetoothAdapter represents the local device bluetooth adapter

写了一个经典蓝牙,但是有一丢丢不稳定,就很烦

//主动连接端
    private fun toConnect() {
        try {

            val socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString(app_uuid))
            Utils.siglePool.execute {
                loopRead(socket!!)
            }
        } catch (e: Exception) {
            closeBluetooth()
            Log.w(MainApplication.TAG, "listerBroad: $e")
        }
    }


//被动接受端
 private fun listerBroad() {
        try {
            val adapter = BluetoothAdapter.getDefaultAdapter()
            socketServer = adapter.listenUsingRfcommWithServiceRecord(BT_NAME, UUID.fromString(app_uuid))
            Utils.siglePool.execute {
                val socket = socketServer?.accept()
                socketServer?.close()//关闭监听,只连接一个设备
                loopRead(socket!!)
            }
        } catch (e: Exception) {
            closeBluetooth()
            Log.w(TAG, "listerBroad: $e")
        }
    }



    /**
     * 读取消息
     */
    fun loopRead(sk: BluetoothSocket) {
        this.socket = sk
        try {
            if (!socket?.isConnected!!) {
                socket?.connect()
            }
            val input = socket?.inputStream
            outPut = socket?.outputStream
            var count = 0
            var already = 0
            val readByte = ByteArray(24)
            isRead = true
            while (((input?.read(readByte)).also { count = it!! }) != -1) {
                already += count
                if (already >= input?.available()!!) {
                    lister?.getSocketDataForBluetooth(bytesToHexString(readByte)!!)
                    isRead = false
                    break
                }
            }
        } catch (e: Exception) {
            isRead = false
            Log.w(TAG, "loopRead: ${e.toString()}")
        }

    }
   /**
     * 发送消息
     */
fun sendData(msg: String) {
        if (isSend) {
            Log.w(TAG, "sendData: 发送中")
            return
        }
        isSend = true
        try {
            outPut?.write(hexStringToBytes(msg))
            outPut?.flush()
        } catch (e: java.lang.Exception) {
            isSend = false
            Log.w(TAG, "loopRead: ${e.toString()}")
            lister?.finishSendData(false, msg)
        }
        lister?.finishSendData(true, msg)
    }

你可能感兴趣的:(Android Bluetooth)