安卓Android BLE低功耗藍牙接受數據詳解 只需100行代碼輕鬆搞定

做了一個安卓手機通過藍牙獲取電子秤的重量的Demo,在此寫下以供大家參考和討論.

先上代碼,着急用的可以迅速參考,後面再寫說明
我跳過了掃描過程,直接根據藍牙設備地址進行連接,可以運行官方Demo來獲取藍牙設備地址以及UUID

/**
 * 藍牙接收數據Demo
 * 藍牙地址和UUID可以通過BLE官方Demo來獲取
 */
public class MainActivity extends AppCompatActivity {

    private TextView tv;
    private ScrollView sv;

    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGatt mBluetoothGatt;

    private String mDeviceAddress = "00:15:83:30:80:CC";//藍牙設備地址

    public final static UUID UUID_SERVICE =
            UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb");//藍牙設備的Service的UUID

    public final static UUID UUID_NOTIFY =
            UUID.fromString("0000ffe1-0000-1000-8000-00805f9b34fb");//藍牙設備的Characteristic的UUID

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            tv.append((String) msg.obj);
            sv.fullScroll(View.FOCUS_DOWN);

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.tv);
        sv = (ScrollView) findViewById(R.id.sv);

        //獲取BluetoothManager
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        //獲取BluetoothAdapter
        mBluetoothAdapter = mBluetoothManager.getAdapter();

        //如果藍牙沒有打開 打開藍牙
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }

        //根據藍牙地址獲取BluetoothDevice
        BluetoothDevice bluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);

        //如果Gatt在運行,將其關閉
        if (mBluetoothGatt != null) {
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }
        //連接藍牙設備並獲取Gatt對象
        mBluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this, true, bluetoothGattCallback);


    }

    /**
     * 藍牙返回數據函數
     * 方法體在service中,不得在方法體中使用更新界面的操作以及Toast,否則程序無法運行!!!
     */
    private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {//連接狀態改變
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (newState == BluetoothProfile.STATE_CONNECTED) {//連接成功
                    setText("連接成功");
                    //搜索Service
                    mBluetoothGatt.discoverServices();
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {//斷開連接
                    setText("連接斷開");
                }
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {//服務被發現
            //根據UUID獲取Service中的Characteristic,並傳入Gatt中
            mBluetoothGatt.setCharacteristicNotification(gatt.getService(UUID_SERVICE).getCharacteristic(UUID_NOTIFY), true);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {//數據改變
            String data = new String(characteristic.getValue());
            Log.e("log", data);
            setText(data);

        }

    };

    //添加文本
    private void setText(String text) {
        Message message = new Message();
        message.obj = text;
        handler.sendMessage(message);
    }

    //關閉Activity的時候需要關閉Gatt
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBluetoothGatt.close();
        mBluetoothGatt = null;
    }

}

可以先下載官方BLEDemo,用來搜索BLE設備以及獲取藍牙地址和UUID
我是從這個哥們這裏下載的http://download.csdn.net/download/lqw770737185/8116019

官方Demo使用方法
主界面,上面的條目即爲搜索到的藍牙設備
如:BT05爲藍牙設備名 ,00:15:83:30:80:CC爲藍牙地址
這裏寫圖片描述

點進去之後爲藍牙設備中的service,點開service裏面有characteristic,characteristic中含有需要的數據
這裏寫圖片描述
點擊最後一個characteristic的效果
圖中的標紅數字即爲我需要的數據
記錄下service的UUID和characteristic的UUID,以供使用
這裏寫圖片描述

代碼量並不多,註釋也比較詳細,大家可以直接看上面代碼

需要注意的是在bluetoothGattCallback方法在一個Service中,不能在方法體中進行更新界面或者Toast.
下面放源碼,不過需要更改藍牙地址和UUID才能使用,修改成自己的設備的地址和UUID.
CSDN:http://download.csdn.net/download/woqq863787405/9691490
網盤:https://pan.baidu.com/s/1b8t5oi

最後,我只是剛入門的新手,可能有的地方不對或者不漏洞,歡迎大家指出.

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