安卓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

最后,我只是刚入门的新手,可能有的地方不对或者不漏洞,欢迎大家指出.

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值