android!蓝牙BLE

来源:互联网 发布:java deletecharat 编辑:程序博客网 时间:2024/04/28 22:01

废话不多,先上代码:
蓝牙BLE:
第一步:蓝牙适配器

BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);adapter = bluetoothManager.getAdapter();      if(!adapter.isEnabled()){    //如果蓝牙设备不可用的话,创建一个intent对象,该对象用于启动一个Activity,提示用户启动蓝牙适配器    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    startActivity(intent);}    scanLeDevice(true);}

第二步,scanLeDevice

// 扫描ble设备函数private void scanLeDevice(boolean enable) {    if (enable) {        // Stops scanning after a pre-defined scan period.        mHandler.postDelayed(new Runnable() {            @Override            public void run() {                mScanning = false;                adapter.stopLeScan(mLeScanCallback);                }            }        }, SCAN_PERIOD);        mScanning = true;        adapter.startLeScan(mLeScanCallback);    } else {        mScanning = false;        adapter.stopLeScan(mLeScanCallback);    }}

第三步:mLeScanCallback的声明

    // Device scan callback.    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() {                    System.err.println(device.getAddress()+"*"+device.getName());                    bluetoothDevicesSet.add(device);                }            });        }    };

此时,你应该已经可以打印出获得的设备,你可以将它们放在一个listview中,并对此listview设置监听:

// 点击列表中的设备名称listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){   @Override   public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,                           long arg3) {       // 建立链接       BluetoothDevice btd = bluetoothDevicesList.get(arg2);       bluetoothGatt = btd.connectGatt(getApplicationContext(), false, gattCallback);       System.out.println(bluetoothGatt.connect());       System.out.println(bluetoothGatt.discoverServices());   }});

接下来是gattCallback的声明:

private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {        @Override        public void onConnectionStateChange(BluetoothGatt gatt, int status,                                            int newState) {            String intentAction;            if (newState == BluetoothProfile.STATE_CONNECTED) {                //intentAction = ACTION_GATT_CONNECTED;                mConnectionState = STATE_CONNECTED;                //broadcastUpdate(intentAction);                Log.i(TAG, "Connected to GATT server.");                Log.i(TAG, "Attempting to start service discovery:" +                        bluetoothGatt.discoverServices());            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {                //intentAction = ACTION_GATT_DISCONNECTED;                mConnectionState = STATE_DISCONNECTED;                Log.i(TAG, "Disconnected from GATT server.");                //broadcastUpdate(intentAction);            }        }        @Override        // New services discovered        public void onServicesDiscovered(BluetoothGatt gatt, int status) {            if (status == BluetoothGatt.GATT_SUCCESS) {                //broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);                Log.i(TAG, "BluetoothGatt.GATT_SUCCES:" + status);                // 连接成功                List<BluetoothGattService> gattServiceList = gatt.getServices();                for (BluetoothGattService gattService : gattServiceList){                    List<BluetoothGattCharacteristic> gattCharacteristics =gattService.getCharacteristics();                    for (final BluetoothGattCharacteristic gattCharacteristic: gattCharacteristics) {                        //UUID_KEY_DATA是可以跟蓝牙模块串口通信的Characteristic                        if(gattCharacteristic.getUuid().toString().equals("adabfb02-6e7d-4601-bda2-bffaa68956ba")){                            //测试读取当前Characteristic数据,会触发mOnDataAvailable.onCharacteristicRead()//                            mHandler.postDelayed(new Runnable() {//                                @Override//                                public void run() {//                                    gatt.readCharacteristic(gattCharacteristic);//                                }//                            }, 500);                            //接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()                            gatt.setCharacteristicNotification(gattCharacteristic, true);                            //设置数据内容                            gattCharacteristic.setValue("1234567");                            //往蓝牙模块写入数据                            System.out.println("writeCharacteristic*"+gatt.writeCharacteristic(gattCharacteristic));                        }                    }                }            } else {                Log.w(TAG, "onServicesDiscovered received: " + status);            }        }    };

好多代码啊~现在差不多了~~

0 0
原创粉丝点击