android 蓝牙4.0入门开发

针对一对一的蓝牙进行通讯,适合没有开发过蓝牙的同学来看,也适合大部分物联网简单开发,没有深入蓝牙的开发。对于没有开发过蓝牙的来说,我先说下逻辑。比如先拿自己手机的蓝牙来说,打开蓝牙,列出列表,包含已经配对过的和可用设备, 点击其中一个进行配对,配对完成就可以进行文件传输等通信功能了。所以对于蓝牙开发,大致以下步骤
1.打开蓝牙
2.蓝牙扫描,列出可用设备
3.关闭蓝牙扫描(不关闭会一直扫描)
4.找到目标蓝牙设备进行连接
5.连接成功,进行通信
6.关闭蓝牙释放资源
接下来我们要根据上面6个步骤进行API的说明,在说明前,我先说明一下
(1)Service蓝牙功能集合,每一个Service都有一个UUID,
(2)Characteristic 在service中也有好多个Characteristic 独立数据项,其中也有独立UUID
上面的两个uuid需要从硬件工程师中获取,这样你才能匹配到你要的。
(3)BluetoothAdapter 蓝牙的打开关闭等基本操作
(4)BluetoothDevice 蓝牙设备,扫描到的
(5)BluetoothGatt 蓝牙连接重连断开连接等操作的类
(6)BluetoothGattCharacteristic 数据通信操作类,读写等操作
1.打开蓝牙
需要权限

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

BluetoothAdapter 这个类就是蓝牙的基本操作,比如打开关闭等
初始化蓝牙,得到BluetoothAdapter
private void initBlueTooth() {
//首先看是否有蓝牙或者开着
    BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
    if (manager != null) {
        bluetoothAdapter = manager.getAdapter();
        if (bluetoothAdapter != null) {
            //蓝牙没有打开
            if (!bluetoothAdapter.isEnabled()) {
                openBle();
            } else {
                Toast.makeText(MainActivity.this, "蓝牙已打开", Toast.LENGTH_SHORT).show();
                scanLeDevice(true);
            }
        } else {
            openBle();
        }
    }
}

打开蓝牙
   private void openBle() {
   //以下两种方式 第二种方式在onActivityResult处理回调
//        boolean enable = bluetoothAdapter.enable();//打开蓝牙'直接打开,用户不知权,用于定制系统'
//        Toast.makeText(MainActivity.this, "正在打开蓝牙", Toast.LENGTH_SHORT).show();
//        if (enable) {
//            Log.e("open",enable+"");
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    scanLeDevice(true);
//                }
//            },2000);
//
//        }
​
        //提示用户正在打开蓝牙
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
​
​
    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == REQUEST_ENABLE_BT) {
        scanLeDevice(true);
    }
}

2.3.打开或者停止扫描,放在同一个方法中
/**
 * 打开或者停止扫描
 *
 * @param enable
 */
private void scanLeDevice(final boolean enable) {
​
    if (enable) {	
        mScanning = true;
        // 定义一个回调接口供扫描结束处理
        bluetoothAdapter.startLeScan(mLeScanCallback);
        // 预先定义停止蓝牙扫描的时间(因为蓝牙扫描需要消耗较多的电量)
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mScanning = false;
                bluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        }, SCAN_PERIOD);
​
    } else {
        mScanning = false;
        bluetoothAdapter.stopLeScan(mLeScanCallback);
    }
}

扫描回调,回调之后得到 BluetoothDevice 的集合,可以放到列表中去
/**
 * 扫描回调
 */
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
        if (bluetoothDevice.getName() != null) {
            if (!bluetoothDeviceArrayList.contains(bluetoothDevice)) {//去下重
                bluetoothDeviceArrayList.add(bluetoothDevice);
            }
            Log.e(TAG, "scan--" + bluetoothDevice.getName());
        }
    }
};

4.5.进行蓝牙连接
/**
 * 连接蓝牙 参数为目标设备
/
public void connectBle(BluetoothDevice bluetoothDevice) {
    mBluetoothDevice = bluetoothDevice;
    if (bluetoothDevice != null) {
        //第二个参数 是否重连
        mBluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this, false, bluetoothGattCallback);
    }
​
}

连接回调
  /**
     * 蓝牙连接成功回调
     */
​
    private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @Override
        public void onPhyUpdate(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
            super.onPhyUpdate(gatt, txPhy, rxPhy, status);
        }
​
        @Override
        public void onPhyRead(BluetoothGatt gatt, int txPhy, int rxPhy, int status) {
            super.onPhyRead(gatt, txPhy, rxPhy, status);
        }
​
        //不要执行耗时操作
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {//连接成功
                Log.e(TAG, "onConnectionStateChange 蓝牙连接");
                //这里要执行以下方法,会在onServicesDiscovered这个方法中回调,如果在                        //onServicesDiscovered方法中回调成功,设备才真正连接起来,正常通信
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Log.e(TAG, "onConnectionStateChange 蓝牙断连");
                if (mBluetoothDevice != null) {
                    //关闭当前新的连接
                    gatt.close();
                    characteristic = null;
                 
                }
​
            }
​
        }
​
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            //回调之后,设备之间才真正通信连接起来
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.e(TAG, "onServicesDiscovered 蓝牙连接正常");
                BluetoothGattService service = gatt.getService(UUID.fromString(BleConstantValue.serverUuid));//uuid从硬件工程师获取
                characteristic = service.getCharacteristic(UUID.fromString(BleConstantValue.charaUuid));
                gatt.readCharacteristic(characteristic);//执行之后,会执行下面的                onCharacteristicRead的回调方法
                //设置通知,一般设备给手机发送数据,需要以下监听
                setCharacteristicNotification(characteristic, true);
                //耗时操作,如果有ui操作,需要用到handler
                adapterFreshHandler.sendEmptyMessage(0);
            } else {
                Log.e(TAG, "onServicesDiscovered 蓝牙连接失败");
            }
​
        }
​
        //这个方法一般用不到
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            Log.e(TAG, "callback characteristic read status " + status
                    + " in thread " + Thread.currentThread());
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.e(TAG, "read value: " + characteristic.getValue());
            }
​
​
        }
​
        //这个方法是写入数据时的回调,可以和你写入的数据做对比
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            Log.e(TAG, "write value: " + FormatUtil.bytesToHexString(characteristic.getValue()));
        }
​
        //设备发出通知时会调用到该接口,蓝牙设备给手机发送数据,在这个方法接收
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            Log.e(TAG, "接收:" + FormatUtil.bytesToHexString(characteristic.getValue()));//byte[]转为16进制字符串
            bleWriteReceiveCallback();
        }
    };

​
/**
* 设置通知
/
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
        if (bluetoothAdapter == null || mBluetoothGatt == null) {
            return;
        }
        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    }

参考写入指令
/**
 * 写入命令
 */
private void write(byte[] cmd) {
    if (characteristic != null) {
        // 发出数据
        characteristic.setValue(cmd);
        if (mBluetoothGatt.writeCharacteristic(characteristic)) {
            Log.e(TAG, "写入成功");
        } else {
            Log.e(TAG, "写入失败");
        }
    } else {
        Toast.makeText(MainActivity.this, "蓝牙未连接", Toast.LENGTH_SHORT).show();
    }
}

6.断开连接 释放资源
/**
 * 断开蓝牙设备
 */
public void bleDisConnectDevice(BluetoothDevice device) {
    if (mBluetoothGatt != null) {
        mBluetoothGatt.disconnect();
    }
}
​
 /**
     * 释放资源 
     */
​
    private void releaseResource() {
        Log.e(TAG, "断开蓝牙连接,释放资源");
        if (mBluetoothGatt != null) {
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
        }
    }

最后别忘了蓝牙广播:
 /**
     * 注册蓝牙监听广播
     */
    private void registerBleListenerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(bleListenerReceiver, intentFilter);
    }

 /**
     * 蓝牙监听广播接受者
     */
    private BroadcastReceiver bleListenerReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
        //连接的设备信息
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        Log.e(TAG, "蓝牙广播" + action);

        if (mBluetoothDevice != null && mBluetoothDevice.equals(device)) {
            Log.e(TAG, "收到广播-->是当前连接的蓝牙设备");

            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                Log.e(TAG,"广播 蓝牙已经连接");

            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                Log.e(TAG,"广播 蓝牙断开连接");
            }
        } else {
            Log.e(TAG, "收到广播-->不是当前连接的蓝牙设备");
        }

        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    Log.e(TAG, "STATE_OFF 蓝牙关闭");
                    adapter.clear();
                    releaseResource();
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.e(TAG, "STATE_TURNING_OFF 蓝牙正在关闭");
                    //停止蓝牙扫描
                    scanLeDevice(false);
                    break;
                case BluetoothAdapter.STATE_ON:
                    Log.d(TAG, "STATE_ON 蓝牙开启");
                    //扫描蓝牙设备
                    scanLeDevice(true);
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.e(TAG, "STATE_TURNING_ON 蓝牙正在开启");
                    break;
            }
        }
        }
    };



总结:
蓝牙是一种能够发送或接受两个不同的设备之间传输的数据。 Android平台包含了蓝牙框架,使设备以无线方式与其他蓝牙设备进行数据交换的支持。

Android提供蓝牙API来执行这些不同的操作。
扫描其他蓝牙设备
获取配对设备列表
连接到通过服务发现其他设备
Android提供BluetoothAdapter类蓝牙通信。通过调用创建的对象的静态方法getDefaultAdapter()。其语法如下给出。
private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();
为了使用设备的蓝牙,调用下列蓝牙ACTION_REQUEST_ENABLE的意图。其语法如下:
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);       
除了这个常量,有提供其它的API,支持不同任务的其他常数。它们在下面列出。
Sr.No 常数说明
1 ACTION_REQUEST_DISCOVERABLE 此常数用于开启蓝牙的发现
2 ACTION_STATE_CHANGED 此常量将通知蓝牙状态已经改变
3 ACTION_FOUND 此常数用于接收关于所发现的每个设备的信息
启用了蓝牙功能之后,可以通过调用 getBondedDevices()方法来获取配对设备列表。它返回一组的蓝牙设备。其语法如下:
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
除了配对的设备,还有API,让更多蓝牙控制权等方法。它们在下面列出。
Sr.No 方法及说明
1 enable() 这种方法使适配器,如果未启用
2 isEnabled() 如果适配器已启用此方法返回true
3 disable() 该方法禁用适配器
4 getName() 此方法返回的蓝牙适配器的名称
5 setName(String name) 此方法更改蓝牙名称
6 getState() 此方法返回蓝牙适配器的当前状态
7 startDiscovery() 此方法开始蓝牙120秒的发现过程。
示例
这个例子提供了示范BluetoothAdapter类操纵蓝牙,并显示通过蓝牙配对设备列表。
为了试验这个例子,需要在实际设备上运行此程序
步骤 描述
1 使用Android Studio创建Android应用程序,并将其命名为Bluetooth,创建这个项目,确保目标SDK编译在Android SDK的最新版本或使用更高级别的API。
2 修改 src/MainActivity.java 文件中添加代码
3 如果修改所需的布局XML文件 res/layout/activity_main.xml 添加GUI组件
4 修改 res/values/string.xml 文件,并添加必要的字符串常量组件
5 修改 AndroidManifest.xml 添加必要的权限。
6 运行应用程序并选择运行Android的设备,并在其上安装的应用和验证结果。

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值