Android BLE 蓝牙的一些总结

 https://github.com/Jasonchenlijian/FastBle

0.下载依赖库,添加库

1对蓝牙初始化和权限声明

1.1声明权限(AndroidManifest.xml中)





1.2在AndroidManifest.xml中还需要初始化蓝牙,我们新建一个class比如BleApplication,其中个代码如下:

 @Override
    public void onCreate() {
        super.onCreate();
        BleManager.getInstance().init(this);
        BleManager.getInstance()
                .enableLog(true)
                .setMaxConnectCount(7)
                .setOperateTimeout(5000);

1.3之后在AndroidManifest.xml中运用

2.在Activity中写蓝牙搜索,连接的代码

可以用一个BleManager变量,因为之后会用到很多次BleManager.getInstance();

 private BleManager bleManager;

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bleManager = BleManager.getInstance();

 

2.1在生命周期onResume中 判断有无蓝牙连接,如果没有就开始检查蓝牙状态和搜索蓝牙.

这有三个方法checkBluetoothState(), searchBluetoothDevices(),showConnectedDevice()

 

@Override
    protected void onResume() {
        super.onResume();

        //检查蓝牙连接
        if (BleManager.getInstance().getAllConnectedDevice().size() == 0){
            checkBluetoothState();
            searchBluetoothDevices();
           
        }else
        {
            showConnectedDevice();
        }
    }

 

2.2几个方法的代码:

 2.2.1checkBluetoothState()

//检测蓝牙打开情况
    private void checkBluetoothState(){
        if (!bleManager.isBlueEnable()){
            //判断是否打开蓝牙
            AlertDialog.Builder builder = new AlertDialog.Builder(BleSearchActivity.this);
            builder.setTitle(R.string.ble_tips) //标题
                    .setMessage(R.string.ble_connect_suggestion) //提示内容
                    .setPositiveButton(R.string.positive_bt, new DialogInterface.OnClickListener() { //确定按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton(R.string.negative_bt,null);
            builder.show();
        }
    }

2.2.2 searchBluetoothDevices()

private void searchBluetoothDevices(){
        bleManager.disconnectAllDevice();
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, R.string.open_ble, Toast.LENGTH_LONG).show();
            return;
        }


        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
               //检查权限
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

2.2.2.1 onPermissionGranted

//检查权限
    private void onPermissionGranted(String permission) {
        //确定配置了 位置信息 权限
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    new android.app.AlertDialog.Builder(this)
                            .setTitle(R.string.ble_tips)
                            .setMessage(R.string.gps_notify)
                            .setNegativeButton(R.string.negative_bt,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton(R.string.set_gprs_tips,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                } else {
                   
                    startScan();
                }
                break;
        }
    }

2.2.2.1.1  checkGPSIsOpen()

private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }

2.2.2.1.2  startScan()开始扫描蓝牙

 //开始扫描
    private void startScan() {
        //设置扫描规则
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                //     .setServiceUuids(serviceUuids)      // 只扫描指定的服务的设备,可选
                //    .setDeviceName(true, null)   // 只扫描指定广播名的设备,可选
                //    .setDeviceMac("34:81:F4:16:60:4F")     // 只扫描指定mac的设备,可选
                //     .setAutoConnect(isAutoConnect)      // 连接时的autoConnect参数,可选,默认false
                .setScanTimeOut(5000)              // 扫描超时时间,可选,默认10秒
                .build();
        bleManager.initScanRule(scanRuleConfig);



        bleManager.scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                mDeviceAdapter.clearScanDevice();
                mDeviceAdapter.notifyDataSetChanged();
              
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                if (bleDevice.getName() != null){
                    mDeviceAdapter.addDevice(bleDevice);
                    mDeviceAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onScanFinished(List scanResultList) {
              
            }
        });
    }

 

3.在列表中显示搜到的蓝牙,通过点击连接,用到listview

 3.1点击连接蓝牙的代码

 private void connect(final BleDevice bleDevice){
        bleManager.connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                simpleDialog.setMessage("waiting..");
                simpleDialog.show();
            }

            @Override
            public void onConnectFail(BleException exception) {
                simpleDialog.dismiss(); 
                Toast.makeText(BleSearchActivity.this, R.string.label_failed,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                mBleDevice = bleDevice;
                simpleDialog.dismiss();

                mDeviceAdapter.removeDevice(bleDevice);
                mDeviceAdapter.notifyDataSetChanged();
                mBleStatus.setText(bleDevice.getName());
                mBleStatus.setTextColor(0xFF1DE9B6);
                setMtu(bleDevice,27);

            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                mDeviceAdapter.removeDevice(device);
                mDeviceAdapter.notifyDataSetChanged();

                mBleStatus.setText(R.string.noconnect_label);
                mBleStatus.setTextColor(getResources().getColor(R.color.ivory));
                ConnectObManager.getInstance().notifyObserver(bleDevice);
            }
        });
    }
设置传输单元的最大长度
private void setMtu(BleDevice bleDevice, int mtu) {
        BleManager.getInstance().setMtu(bleDevice, mtu, new BleMtuChangedCallback() {
            @Override
            public void onSetMTUFailure(BleException exception) {
               // MyLog.i(TAG, "onsetMTUFailure" + exception.toString());
            }

            @Override
            public void onMtuChanged(int mtu) {
               // MyLog.i(TAG, "onMtuChanged: " + mtu);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                MainActivity.actionStart(BleSearchActivity.this,"");
                finish();
            }
        });
    }

列表代码

 mDeviceAdapter = new DeviceAdapter(this);
        mDeviceAdapter.setOnDeviceClickListener(new DeviceAdapter.OnDeviceClickListener() {
            @Override
            public void onConnect(BleDevice bleDevice) {
                if (!BleManager.getInstance().isConnected(bleDevice)) {
                    BleManager.getInstance().cancelScan();
                    connect(bleDevice);
                }
            }

            @Override
            public void onDisConnect(BleDevice bleDevice) {
                if (BleManager.getInstance().isConnected(bleDevice)) {
                    BleManager.getInstance().disconnect(bleDevice);
                }
            }
        });
        ListView listView_device = (ListView) findViewById(R.id.liv_ble_device);
        listView_device.setAdapter(mDeviceAdapter);

警告对话框代码

simpleDialog = new ProgressDialog(this);
        simpleDialog.setCanceledOnTouchOutside(false);

        //对话框取消的监听
        simpleDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (!BleManager.getInstance().isConnected(mBleDevice)) {
                    //MyLog.i(TAG, "进度框取消");
                    BleManager.getInstance().destroy();
                    simpleDialog.dismiss();
                    BleManager.getInstance().init(getApplication());
                }
            }
        });

 

你可能感兴趣的:(Android BLE 蓝牙的一些总结)