BLE藍牙

這麼說不對,但是我覺得這麼理解比較好理解,藍牙分爲重量級和輕量級,輕量級的連接是在藍牙4.0以上纔有的,也就是 BLE技術 , 而Android是在API 18 也就是4.3以上才支持藍牙4.0技術。BLE更省電,連接速度更快,使用3個連接通道,而普通的藍牙連接則使用了32個,下面就來介紹着兩種方式。

重量級藍牙

- BluetoothManager
- BluetoothAdapter
- BluetoothServiceSocket
- BluetoothSocket

不管是輕量級連接還是重量級連接,都需要這兩個類Manager 和 Adapter,步驟是這樣的:
1. 通過.getSystemService(Context.BLUETOOTH_SERVICE);得到Manager
2. 通過manager.getAdapter()得到adapter,
3. 通過adapter搜索。
4. 註冊廣播,來接收搜索到的設備信息。更多代碼請看下面的連接,藍牙一般使用。

打開藍牙:

Intent enabler = new Intent(MyBluetoothAdapter.ACTION_REQUEST_ENABLE);
((Activity) mContext).startActivityForResult(enabler, 0x1);

註冊廣播:

BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                //找到設備
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                }
        }
}

之後就可以通過這個device來得到IO流,再具體的還是看下面的連接,藍牙的一般使用。

BLE藍牙

前兩步和重量級連接一樣,那個步驟,不同的是得到adapter之後,下面是具體代碼:

/**
 * 藍牙管理模塊
 * Created by R on 2015/8/4.
 */
public class BluetoothManager {

    private Context mContext;
    /**
     * 藍牙適配器
     */
    private BluetoothAdapter mAdapter;
    /**
     * BLE設備
     */
    private BluetoothGatt mBluetoothGatt;

    /**
     * —————————————————————— 單例呀單例 ——————————————————————————
     */
    private static BluetoothManager instance;

    private BluetoothManager(Context context) {
        mContext = context;
        initBluetooth();
    }

    public static BluetoothManager getInstance(Context context) {
        if (instance == null) {
            synchronized (BluetoothManager.class) {
                if (instance == null) {
                    if(context == null){
                        return null;
                    }
                    instance = new BluetoothManager(context);
                }
            }
        }
        return instance;
    }

    /**
     * 初始化藍牙
     */
    private void initBluetooth() {
        android.bluetooth.BluetoothManager manager = (android.bluetooth.BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE);
        mAdapter = manager.getAdapter();
    }

    /**
     * 打開藍牙
     * @return
     */
    public boolean openBluetooth() {
        if (!isEnabled()) {
//            Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            ((Activity) mContext).startActivityForResult(enabler, 0x1);
            return mAdapter.enable();
        }
        return false;
    }

    /**
     * 關閉藍牙
     * @return
     */
    public boolean closeBluetooth(){
        if(isEnabled()){
            return mAdapter.disable();
        }
        return false;
    }

    /**
     * 開始搜索BLE設備
     * @param callback
     */
    public void startSearchOfLe(BluetoothAdapter.LeScanCallback callback){
        if(!isEnabled()){
            openBluetooth();
        }
        mAdapter.startLeScan(callback);
    }

    /**
     * 停止搜索設備
     */
    public void stopSearchOfLe(BluetoothAdapter.LeScanCallback callback) {
        if (isEnabled()){
            mAdapter.stopLeScan(callback);
        }
    }

    /**
     * 返回藍牙是否可用
     * @return
     */
    public boolean isEnabled(){
        return mAdapter.isEnabled();
    }

    /**
     * 連接
     */
    public void connectionOfGatt(BluetoothDevice device , BluetoothGattCallback callback){
        if(device != null || callback == null){
            mBluetoothGatt = device.connectGatt(mContext, true, callback);
        }
    }

    public BluetoothGatt getGatt(){
        return mBluetoothGatt;
    }

}

這個代碼其實沒什麼用,就是一些基本操作,關鍵在這裏:

連接Gatt的步驟:
1. 打開藍牙
2. 通過Manager拿到Adapter
3. 通過adapter搜索BLE設備,搜索的時候會讓你傳入一個LeScanCallback實現類用做回調。
4. 搜索到設備的時候,會去調用onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) 方法告訴你找到設備了。第一個參數是硬件設備,第二個是藍牙距離,第三個是藍牙的廣播,比如說我們的產品就是吧一個16進制的SN號以byte[]寫了進去。
5. 然後調用device.connectionGatt();連接BLE設備,這時你需要傳入一個BluetoothGattCallback的實現類用作回調,這個回調就熱鬧了,具體的看API和參考博客, 在這裏我只用到了onConnectionStateChange(BluetoothGatt gatt, int status, int newState) 、 onServicesDiscovered(BluetoothGatt gatt, int status)、onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) 方法。下面會詳細說明。
6. 當你調用device.connectionGatt() 連接到設備之後,會回調onConnectionStateChange,他會返回一個Gatt對象,這個東西就相當於你的BLE設備了,其實到這裏我也沒搞清楚,因爲按說就可以通過Gatt對象得到Service然後在得到BluetoothGattCharacteristic , 然後使用BluetoothGattCharacteristic的setValue()方法扔進去一個byte[]數組,再調用gatt.writeCharacteristic()吧之前的BluetoothGattCharacteristic扔進去就好了,但是不知道爲什麼我這裏是獲取不到Service的,必須要在onServicesDiscovered這個回調裏才能得到Service。所以我是在onServicesDiscovered這個回調裏完成上面步驟的。
7. 最後,當你完成上面步驟的時候,會有onCharacteristicWrite的回調,來告訴你是否寫入成功了。
8. 接收數據,這個就簡單了,做到這裏就已經沒什麼挑戰性了,就跟從初戀到老夫老妻了一樣,自己去看onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,intstatus)這個方法吧,只要有消息都會去回調這個方法的,哦 還有,這之前別忘了先訂閱一下:
BluetoothGattCharacteristic read = service.getCharacteristic(UUID.fromString(ConstantsOfBluetooth.UUID_READ));

參考鏈接

http://blog.csdn.net/wave_1102/article/details/39271693 這個好!!

http://blog.csdn.net/xubin341719/article/details/38584469 看不懂的藍牙底層詳解

http://www.cnblogs.com/freeliver54/archive/2011/12/13/2285980.html 藍牙一般使用

http://www.2cto.com/kf/201411/349575.html 藍牙4.0總結

http://blog.csdn.net/woshasanguo/article/details/41082395 BLE藍牙連接參考的是這個

http://www.cnblogs.com/freeliver54/archive/2011/12/13/2285980.html

http://www.open-open.com/lib/view/open1390879771695.html#_label8 相當於中文API了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章