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<BluetoothDevice> getConnectedDevices()
return the set of devices which are in state STATE_CONNECTED

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

List<BluetoothDevice> 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

寫了一個經(jīng)典藍牙,但是有一丟丟不穩(wěn)定,就很煩

//主動連接端
    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()//關(guān)閉監(jiān)聽,只連接一個設(shè)備
                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()}")
        }

    }
   /**
     * 發(fā)送消息
     */
fun sendData(msg: String) {
        if (isSend) {
            Log.w(TAG, "sendData: 發(fā)送中")
            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)
    }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容