Android 低功耗藍(lán)牙


1.BLE權(quán)限定義

Android低功耗藍(lán)牙只支持4.3(API 18)以后的設(shè)備
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
如果你只想你的APP運(yùn)行在支持低功耗藍(lán)牙的設(shè)備上你可以在manifest上加入
    <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

或者在運(yùn)行時(shí)加入以下代碼:

if (!getPackageManager().hasSystemFeature(
PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
    finish();
}

2.配置藍(lán)牙

2.1.獲取BluetoothAdapter

final BluetoothManager bluetoothManager =
    (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

2.2.打開(kāi)藍(lán)牙

private BluetoothAdapter mBluetoothAdapter;
...
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

3.查找藍(lán)牙設(shè)備


private BluetoothAdapter.LeScanCallback mLeScanCallback =
        new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi,
            byte[] scanRecord) {
        runOnUiThread(new Runnable() {
           @Override
           public void run() {
           
           // 通過(guò) device.getName(),device.getAddress()獲取到藍(lán)牙設(shè)備名稱(chēng)和地址
           }
       });
   }
};


 private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;

    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    ...
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        ...
    }

3.連接藍(lán)牙設(shè)備

private final BluetoothGattCallback mGattCallback =
            new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
            // 連接成功后要查詢(xún)藍(lán)牙服務(wù)
               Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());
                

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
               
            }
        }

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
               //發(fā)現(xiàn)藍(lán)牙服務(wù)后可獲取到
               
            List<BluetoothGattService> gattServices=mBluetoothGatt.getServices();
               
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic,
                int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
            }
        }
     ...
    };
    
BluetoothGatt mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

   // Previously connected device.  Try to reconnect.
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                && mBluetoothGatt != null) {
            Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                mConnectionState = STATE_CONNECTING;
                return true;
            } else {
                return false;
            }
        }

4.獲取藍(lán)牙屬性

在回調(diào)方法onServicesDiscovered中獲取藍(lán)牙設(shè)備的Service和Characteristic;

    @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
             
            List<BluetoothGattService> gattServices=mBluetoothGatt.getServices();
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
               
            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

5.對(duì)藍(lán)牙Characteristic進(jìn)行操作

5.1 寫(xiě)操作(W - Write)
    byte[] dataToWrite;
    characteristic.setValue(dataToWrite)
    mBluetoothGatt.writeCharacteristic(characteristic);
//寫(xiě)操作完成會(huì)回調(diào)
 @Override
     public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
     if (status == BluetoothGatt.GATT_SUCCESS) {
 //寫(xiě)入成功
            }
            else {
             //寫(xiě)入失敗  
            }
     
     }
5.2 讀操作(R - Read)
 mBluetoothGatt.readCharacteristic(characteristic);
//讀操作會(huì)回調(diào)
 @Override
public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic, int status) {
         // we got response regarding our request to fetch characteristic value
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // and it success, so we can get the value
                //在此處取值
                 byte[] rawValue = characteristic.getValue();
            }
        }
5.3 通知或指示操作(I - Indication or N - Notify)
  boolean success = mBluetoothGatt.setCharacteristicNotification(ch, enabled);
        if (!success) {
            Log.e("------", "Seting proper notification status for characteristic failed!");
        }

        BluetoothGattDescriptor descriptor = ch.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
// 啟用或停用  I - Indication or N - Notify
//      BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
//      BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE
    descriptor.setValue(enabled ?
    BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
 mBluetoothGatt.writeDescriptor(descriptor);
// 通知或指示操作會(huì)回調(diào)

   @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            // characteristic's value was updated due to enabled notification, lets get this value
            // the value itself will be reported to the UI inside getCharacteristicValue

            
        }

6.斷開(kāi)連接,關(guān)閉連接

 mBluetoothGatt.disconnect();

public void close() {
    if (mBluetoothGatt == null) {
        return;
    }
    mBluetoothGatt.close();
    mBluetoothGatt = null;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末波桩,一起剝皮案震驚了整個(gè)濱河市风钻,隨后出現(xiàn)的幾起案子曲横,更是在濱河造成了極大的恐慌升敲,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,376評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)权逗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,126評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)冤议,“玉大人斟薇,你說(shuō)我怎么就攤上這事∷∷幔” “怎么了堪滨?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,966評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)蕊温。 經(jīng)常有香客問(wèn)我袱箱,道長(zhǎng)遏乔,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,432評(píng)論 1 283
  • 正文 為了忘掉前任发笔,我火速辦了婚禮盟萨,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘了讨。我一直安慰自己捻激,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,519評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布前计。 她就那樣靜靜地躺著胞谭,像睡著了一般。 火紅的嫁衣襯著肌膚如雪男杈。 梳的紋絲不亂的頭發(fā)上丈屹,一...
    開(kāi)封第一講書(shū)人閱讀 49,792評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音势就,去河邊找鬼。 笑死脉漏,一個(gè)胖子當(dāng)著我的面吹牛苞冯,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播侧巨,決...
    沈念sama閱讀 38,933評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼舅锄,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了司忱?” 一聲冷哼從身側(cè)響起皇忿,我...
    開(kāi)封第一講書(shū)人閱讀 37,701評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎坦仍,沒(méi)想到半個(gè)月后鳍烁,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,143評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡繁扎,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,488評(píng)論 2 327
  • 正文 我和宋清朗相戀三年幔荒,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片梳玫。...
    茶點(diǎn)故事閱讀 38,626評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡爹梁,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出提澎,到底是詐尸還是另有隱情姚垃,我是刑警寧澤,帶...
    沈念sama閱讀 34,292評(píng)論 4 329
  • 正文 年R本政府宣布盼忌,位于F島的核電站积糯,受9級(jí)特大地震影響掂墓,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜絮宁,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,896評(píng)論 3 313
  • 文/蒙蒙 一梆暮、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧绍昂,春花似錦啦粹、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,742評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至忍饰,卻和暖如春贪嫂,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背艾蓝。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來(lái)泰國(guó)打工力崇, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人赢织。 一個(gè)月前我還...
    沈念sama閱讀 46,324評(píng)論 2 360
  • 正文 我出身青樓亮靴,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親于置。 傳聞我的和親對(duì)象是個(gè)殘疾皇子茧吊,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,494評(píng)論 2 348

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