Android 蓝牙BLE功能的开发

写在前面的注意:

  1. 蓝牙4.0要求版本是在4.3(18)以上,所以需要注意一下sdk版本。
  2. 查看蓝牙地址(看型号):设置-->通用-->关于手机-->状态信息-->蓝牙地址

Android BLE 蓝牙4.0开始的低功耗技术。在BLE协议中,有2个角色:周边(periphery)和中央(Central),中央设备扫描,寻找广播;外围设备发出广播。

工作流程:Scan-->Connect-->DiscoverService-->Characteristic-->DisConnect

首先是扫描设备进行连接,连接上扫描设备有什么服务,读写服务里的特征,最后断开连接。
===============================================================================

权限:

        android:required="true"/>//这个feature可加可不加,加了会让App只运行在有相应设备(蓝牙4.0)的机器上

===============================================================================

扫描:

bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

bluetoothAdapter = bluetoothManager.getAdapter();

bluetoothAdapter.startLeScan(scanCallback);

//扫描蓝牙设备的回调

    private BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback(){

        @Override

        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {//在工作线程工作

            String name = device.getName();

            String address = device.getAddress();

            ParcelUuid[] uuid = device.getUuids();

        }

    };

===============================================================================

Client 端代码:

Service:(记得在AndroidManifest.xml注册此服务)

public void onCreate() {
        super.onCreate();
        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        handler = new Handler();
    }
public int onStartCommand(Intent intent, int flags, int startId) {
        int command = intent.getIntExtra(EXTRA_COMMAND,-1);
        switch (command){
            case COMMAND_CONNECT:
                String address = intent.getStringExtra(CONNETC_ADDRESS);
                btDevice = bluetoothAdapter.getRemoteDevice(address);
                bluetoothGatt = btDevice.connectGatt(this, false, gattCallback);
//                bluetoothGatt.connect();//好像不需要这句也可以连接
                break;
            case COMMAND_DISCONNECT:
                if(bluetoothGatt != null){
                    bluetoothGatt.disconnect();
                }
                break;
            case COMMAND_DISCOVER_SERVICE:
                if(bluetoothGatt != null){
                    boolean b = bluetoothGatt.discoverServices();
                }
                break;
            case COMMAND_READ_RSSI:
                if(bluetoothGatt != null){
                    boolean b = bluetoothGatt.readRemoteRssi();
                }
                break;
            case COMMAND_WRITE_CHARACTERISTIC:
                if(bluetoothGatt != null){
                    String msg = intent.getStringExtra(WRITE_VALUE);
                    service = bluetoothGatt.getService(SERVICE_UUID);//对应server端的setService方法
                    characteristic = service.getCharacteristic(CHARACTERISTIC_UUID);//对应server端的setCharacteristic方法
                    characteristic.setValue(msg);
                    bluetoothGatt.writeCharacteristic(characteristic);
//                    service.addCharacteristic(characteristic);
//                    BluetoothGattCharacteristic characteristic = bluetoothAdapter
//                    bluetoothGatt.writeCharacteristic(characteristic);
                }
                break;
        }
        return super.onStartCommand(intent, flags, startId);
    }
private BluetoothGattCallback gattCallback = new BluetoothGattCallback(){//BluetoothGatt的回调方法
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
//            super.onConnectionStateChange(gatt, status, newState);
            if(status == BluetoothGatt.GATT_SUCCESS){
                if(newState == BluetoothProfile.STATE_CONNECTED){
                    showMsg("BLE Connect!!!");
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED){
                    showMsg("BLE DisConnect!!!");
                }
            }
        }
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
//            super.onServicesDiscovered(gatt, status);
            if((status == BluetoothGatt.GATT_SUCCESS) && (gatt.getService(SERVICE_UUID)!=null)){
                showMsg("BLE Discover Service Success!!!");
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if(status == BluetoothGatt.GATT_SUCCESS){
                byte[] value = characteristic.getValue();
                String msg = new String(value);
                showMsg("BLE DWRITE_CHARACTERISTIC:"+msg);
            }
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            if(status == BluetoothGatt.GATT_SUCCESS){
                showMsg("BLE Rssi:"+ rssi);
            }
        }
    };

Activity:

case R.id.btn_scan://扫描蓝牙设备
    bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    bluetoothAdapter = bluetoothManager.getAdapter();
    bluetoothAdapter.startLeScan(scanCallback);
    break;
case R.id.btn_connect://连接蓝牙设备
    String address = et_address.getText().toString();
    intent.putExtra(BleClientService.EXTRA_COMMAND, BleClientService.COMMAND_CONNECT);
    intent.putExtra(BleClientService.CONNETC_ADDRESS,address);
    break;
case R.id.btn_discover:
    intent.putExtra(BleClientService.EXTRA_COMMAND, BleClientService.COMMAND_DISCOVER_SERVICE);
    break;
case R.id.btn_write:
    String msg = et_character.getText().toString();
    intent.putExtra(BleClientService.EXTRA_COMMAND, BleClientService.COMMAND_WRITE_CHARACTERISTIC);
    intent.putExtra(BleClientService.WRITE_VALUE, msg);
    break;
case R.id.btn_rssi:
    intent.putExtra(BleClientService.EXTRA_COMMAND, BleClientService.COMMAND_READ_RSSI);
    break;
case R.id.btn_disconnect:
    intent.putExtra(BleClientService.EXTRA_COMMAND, BleClientService.COMMAND_DISCONNECT);
    break;
startService(intent);

Server端代码:

Service:(记得在AndroidManifest.xml注册此服务)

public static final UUID SERVICE_UUID = UUID.fromString("0000FEE0-0000-1000-8000-00805F9B34FB");
public static final UUID CHARACTERISTIC_UUID = UUID.fromString("0000FEE1-0000-1000-8000-00805F9B34FB");
public void onCreate() {
    super.onCreate();
    bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    gattServer = bluetoothManager.openGattServer(this, gattCallback);

    service = new BluetoothGattService(SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY);
    characteristic = new BluetoothGattCharacteristic(CHARACTERISTIC_UUID,0x0A,0x11);//可读+可写,其中0x0A=0x02+0x08

    service.addCharacteristic(characteristic);//把设备的服务特征加入服务里
    gattServer.addService(service);//把自定义设备的服务加入蓝牙服务中

    intent = new Intent(BLE_SERVER_BROADCAST);
}
private BluetoothGattServerCallback gattCallback = new BluetoothGattServerCallback(){//注意,这里服务端是server回调
    @Override
    public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
        if(status == BluetoothGatt.GATT_SUCCESS){
            String msg = null;
            String deviceName = device.getName();
            if(newState == BluetoothProfile.STATE_CONNECTED){
                msg = deviceName + ": Ble Connected! \n";
                intent.putExtra(BLE_SERVER_MSG,msg);
            }else if(newState == BluetoothProfile.STATE_DISCONNECTED){
                msg = deviceName + ": Ble Disconnected! \n";
                intent.putExtra(BLE_SERVER_MSG,msg);
            }
            sendBroadcast(intent);
        }
    }

    @Override
    public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId,
        BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
        String valueMsg = new String(value);
        String msg = device.getName() + ": "+ valueMsg +"\n";//判断是哪个设备发过来的消息
        intent.putExtra(BLE_SERVER_MSG,msg);
        sendBroadcast(intent);
        if(responseNeeded){//如果需要回复
            gattServer.sendResponse(device,requestId,BluetoothGatt.GATT_SUCCESS,0,null);
        }
    }
};

Activity:

在onCreate方法中:

startService(new Intent(this,BleServerService.class));
//注册广播接收器
IntentFilter filter = new IntentFilter();
filter.addAction(BleServerService.BLE_SERVER_BROADCAST);
registerReceiver(receiver,filter);
private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action == BleServerService.BLE_SERVER_BROADCAST){
                String msg = intent.getStringExtra(BleServerService.BLE_SERVER_MSG);
//                result.append(msg);
//                tv_result.setText(result);
                tv_result.append(msg);//textview可以直接append
            }
        }
    };

=================================================================================

代码下载:

https://download.csdn.net/download/lingbulei/10600172

视频教程:

http://www.iqiyi.com/w_19rtbeswyl.html 

https://pan.baidu.com/s/1i5NofIl?qq-pf-to=pcqq.c2c#list/path=%2FPublic%2FDevBoard%2FFirefly-RK3288%2FVideo%2FFirefly%E5%BC%80%E5%8F%91%E6%9D%BFAndroid%E5%BC%80%E5%8F%91%E6%95%99%E5%AD%A6%E8%A7%86%E9%A2%91&parentPath=%2FPublic%2FDevBoard

你可能感兴趣的:(Android工具)