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

寫(xiě)了一個(gè)經(jīng)典藍(lán)牙于颖,但是有一丟丟不穩(wěn)定呆贿,就很煩

//主動(dòng)連接端
    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")
        }
    }


//被動(dòng)接受端
 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)聽(tīng),只連接一個(gè)設(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)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末森渐,一起剝皮案震驚了整個(gè)濱河市做入,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌同衣,老刑警劉巖竟块,帶你破解...
    沈念sama閱讀 206,311評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異耐齐,居然都是意外死亡浪秘,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)埠况,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)耸携,“玉大人,你說(shuō)我怎么就攤上這事辕翰《嵫埽” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,671評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵喜命,是天一觀的道長(zhǎng)刷后。 經(jīng)常有香客問(wèn)我,道長(zhǎng)渊抄,這世上最難降的妖魔是什么尝胆? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,252評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮护桦,結(jié)果婚禮上含衔,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好贪染,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,253評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布缓呛。 她就那樣靜靜地躺著,像睡著了一般杭隙。 火紅的嫁衣襯著肌膚如雪哟绊。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,031評(píng)論 1 285
  • 那天痰憎,我揣著相機(jī)與錄音票髓,去河邊找鬼。 笑死铣耘,一個(gè)胖子當(dāng)著我的面吹牛洽沟,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蜗细,決...
    沈念sama閱讀 38,340評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼裆操,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了炉媒?” 一聲冷哼從身側(cè)響起踪区,我...
    開(kāi)封第一講書(shū)人閱讀 36,973評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎吊骤,沒(méi)想到半個(gè)月后朽缴,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,466評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡水援,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,937評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了茅郎。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蜗元。...
    茶點(diǎn)故事閱讀 38,039評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖系冗,靈堂內(nèi)的尸體忽然破棺而出奕扣,到底是詐尸還是另有隱情,我是刑警寧澤掌敬,帶...
    沈念sama閱讀 33,701評(píng)論 4 323
  • 正文 年R本政府宣布惯豆,位于F島的核電站,受9級(jí)特大地震影響奔害,放射性物質(zhì)發(fā)生泄漏楷兽。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,254評(píng)論 3 307
  • 文/蒙蒙 一华临、第九天 我趴在偏房一處隱蔽的房頂上張望芯杀。 院中可真熱鬧,春花似錦、人聲如沸揭厚。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,259評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)筛圆。三九已至裂明,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間太援,已是汗流浹背闽晦。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,485評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留粉寞,地道東北人尼荆。 一個(gè)月前我還...
    沈念sama閱讀 45,497評(píng)論 2 354
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像唧垦,于是被迫代替她去往敵國(guó)和親捅儒。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,786評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容