Android蓝牙扫描,配对

Android开发使用到蓝牙一般都是外设的连接,像连接打印机什么的,手机跟手机的使用自带的功能就可以了

使用权限

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <!-- 使用扫描和设置蓝牙的权限(申明这一个权限必须申明上面一个权限) -->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-feature android:name="android.hardware.location.gps"/>
    <!-- 扫描时使用的权限 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

扫描、配对

    private ListView lv_device;
    private Button bt_scan;

    private BluetoothAdapter bluetoothAdapter;
    private BluetoothManager bluetoothManager;
    private final int requestCode = 0;
    private ArrayList<BluetoothDevice> mList = new ArrayList<>();
    private boolean isScanleFlag = false;//是否正在开启蓝牙
    private final long SCANTIME = 1000*60;//设置扫描时间
    private BluetoothAdapter.LeScanCallback callback;//扫描回调
    private boolean isHasDevice = false;//是否已存在
    private boolean isConnectDevice = false;//是否已连接成功
    private BluetoothGattCallback bluetoothGattCallback;//蓝牙连接状态回调

    private DeviceAdapter adapter;

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

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

        initView();
        addListenner();
        initBlue();
        scanLeDevice(true);
    }

    private void initView() {
        lv_device = (ListView) findViewById(R.id.lv_device);
        bt_scan = (Button) findViewById(R.id.bt_scan);

        adapter = new DeviceAdapter(this, mList);
        lv_device.setAdapter(adapter);

    }

    private void initBlue() {
        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()){//是否开启蓝牙
            startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), requestCode);
        }else {//获取已配对蓝牙
            Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
            for (final BluetoothDevice mDevice: devices) {
                mList.add(mDevice);
                mDevice.connectGatt(this, false, bluetoothGattCallback);
            }
        }
    }

    private void addListenner() {
        /**扫描***/
        bt_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isScanleFlag){
                    scanLeDevice(!isScanleFlag);
                }
            }
        });

        /***扫描回调***/
        callback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getAddress().equals(device.getAddress())){
                        isHasDevice = true;
                    }
                }
                if (!isHasDevice && device.getName() !=null){
                    mList.add(device);
                    String name = device.getAddress();
                    adapter.notifyDataSetChanged(mList);
                    Log.e("device", name + "-------" + device.getAddress());
                }
                isHasDevice = false;
            }
        };

        lv_device.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mList.get(position).connectGatt(MainActivity.this, false, bluetoothGattCallback);
            }
        });

        /***蓝牙连接状态回调***/
        bluetoothGattCallback = new BluetoothGattCallback() {
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                super.onConnectionStateChange(gatt, status, newState);
                if (status != BluetoothGatt.GATT_SUCCESS){
                    isConnectDevice = false;
                    Log.e("device", status + "-----onConnectionStateChange--连接失败");
                    gatt.close();
                    return;
                }

                if (newState == BluetoothGatt.STATE_CONNECTED){
                    Log.e("device", "-----onConnectionStateChange--已连接");
                    isConnectDevice = true;
                    gatt.discoverServices();
                }else if (newState == BluetoothGatt.STATE_DISCONNECTED){
                    Log.e("device", "-----onConnectionStateChange--已断开");
                    isConnectDevice = false;
                    gatt.close();
                }
            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                super.onServicesDiscovered(gatt, status);
                Log.e("device", "-----onServicesDiscovered--已建立连接通信");
            }

            @Override
            public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                super.onCharacteristicRead(gatt, characteristic, status);
                Log.e("device", "-----onCharacteristicRead--");
            }

            @Override
            public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                super.onCharacteristicWrite(gatt, characteristic, status);
                Log.e("device", "-----onCharacteristicWrite--");
            }

            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                super.onCharacteristicChanged(gatt, characteristic);
                Log.e("device", "-----onCharacteristicChanged--");
            }

            @Override
            public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                super.onDescriptorRead(gatt, descriptor, status);
                Log.e("device", "-----onDescriptorRead--");
            }

            @Override
            public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                super.onDescriptorWrite(gatt, descriptor, status);
                Log.e("device", "-----onDescriptorWrite--");
            }

            @Override
            public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
                super.onReliableWriteCompleted(gatt, status);
                Log.e("device", "-----onReliableWriteCompleted--");
            }

            @Override
            public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
                super.onReadRemoteRssi(gatt, rssi, status);
                Log.e("device", "-----onReadRemoteRssi--");
            }

            @Override
            public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
                super.onMtuChanged(gatt, mtu, status);
                Log.e("device", "-----onMtuChanged--");
            }
        };
    }

    /***
     * 开启关闭蓝牙扫描
     * @param enable
     */
    private void scanLeDevice(boolean enable){
        if (enable){
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isScanleFlag = false;
                    bluetoothAdapter.stopLeScan(callback);
                    Log.e("device", "-------stop");
                }
            }, SCANTIME);
            isScanleFlag = true;
            bluetoothAdapter.startLeScan(callback);
            Log.e("device", "-------start");
        }else {
            isScanleFlag = false;
            bluetoothAdapter.stopLeScan(callback);
        }
    }
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值