蓝牙app开发教程(蓝牙通信app设计及程序)

网站建设 47 0

今天给各位分享蓝牙app开发教程的知识,其中也会对蓝牙通信app设计及程序进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

iOS蓝牙开发:蓝牙的连接和数据的读写

       蓝牙开发说简单也简单,说不简单也有点难,开发人员在首次开发蓝牙前首先需要搞清楚蓝牙开发的概念,还要了解掌握蓝牙开发的一整套流程,这样才能快速上手开发蓝牙。

      蓝牙开发分为两种模式:管理者模式和中心者模式。管理者模式基本很少用到,相当于iPhone手机作为外设,自己创建服务和特性,然后用其他设备连接iPhone手机;中心者模式一般是大部分情况下都会使用的,使用中心者模式开发相当于iPhone手机作为主机,连接蓝牙外设,下面介绍蓝牙开发的例子就是使用的中心者模式来讲解的。

在这里我还是要推荐下我自己建的iOS开发学习群:680565220,群里都是学ios开发的,如果你正在学习ios ,我欢迎你加入,今天分享的这个案例已经上传到群文件,大家都是软件开发党,不定期分享干货(只有iOS软件开发相关的),包括我自己整理的一份2018最新的iOS进阶资料和高级开发教程

一、关于蓝牙开发的一些重要的理论概念:

1、服务(services):蓝牙外设对外广播的时候一定会有一个服务,有些时候也可以是有多个服务,服务下面包含一些特性,服务可以理解成一个模块的窗口;

2、特征(characteristic):特征存在于服务下面的,一个服务下面可以有多个特征,特征可以理解成具体实现功能的窗口,一般的特性都会有value,也就是特征值,是特征和外界交互的最小单位;

      3、UUID:蓝牙上的唯一标示符,为了区分不同服务和特征,就用UUID来表示。

二、蓝牙连接的主要步骤

     1、创建一个CBCentralManager实例来进行蓝牙管理;

     2、搜索扫描外围设备;

     3、连接外围设备;

     4、获得外围设备的服务;

     5、获得服务的特征;

     6、从外围设备读取数据;

     7、给外围设备发送(写入)数据。

三、蓝牙连接和数据读写的具体步骤

     1、导入苹果系统蓝牙框架

#import

     2、遵循两个蓝牙框架相关的协议

     3、新建两个实例属性,一个特征属性

@property (nonatomic, strong) CBCentralManager *centralManager; //中心管理者

@property (nonatomic, strong) CBPeripheral *peripheral; //连接到的外设

@property (nonatomic, strong) CBCharacteristic *characteristic; //特征

     4、初始化CBCentralManager,进行蓝牙管理

- (void)viewDidLoad {

[super viewDidLoad];

self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];     //创建实例进行蓝牙管理

}

 //若中心管理者初始化之后 就会触发下面这个代理方法 该代理方法是用来判断手机蓝牙的状态的

- (void)centralManagerDidUpdateState:(CBCentralManager *)central {

// 蓝牙可用,开始扫描外设

if (central.state == CBManagerStatePoweredOn) {

NSLog(@"蓝牙可用");

//在中心管理者成功开启之后再进行一些操作

//搜索扫描外设

// 根据SERVICE_UUID来扫描外设,如果不设置SERVICE_UUID,则扫描所有蓝牙设备

// [self.centralManager startAdvertising:@{CBAdvertisementDataServiceUUIDsKey:@[[CBUUID UUIDWithString:SERVICE_UUID]]}];

[central scanForPeripheralsWithServices:nil options:nil];

}

if(central.state == CBManagerStateUnsupported) {

NSLog(@"该设备不支持蓝牙");

}

if (central.state == CBManagerStatePoweredOff) {

NSLog(@"蓝牙已关闭");

}

if (central.state == CBManagerStateUnknown) {

NSLog(@"蓝牙当前状态不明确");

}

if (central.state == CBManagerStateUnauthorized) {

NSLog(@"蓝牙未被授权");

}

}

      5、搜索外围设备

//执行扫描动作之后,如果扫描到外设了,就会自动回调下面的协议方法

/** 发现符合要求的外设,回调 */

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {

NSLog(@"%@====",peripheral.name);

//根据外设名字有选择性的筛选连接蓝牙设备

if ([peripheral.name hasPrefix:@"TEAMOSA"]) {

//在这里对外设携带的广播数据进行进一步的处理

if ([self.peripheraNames containsObject:peripheral.name]) {

//如果数组中包含了就不再添加

return;

}

//添加到外设名字数组中

[self.peripheraNames addObject:peripheral.name];

//标记外设,让它的生命周期与控制器的一致

self.peripheral = peripheral;

// 可以根据外设名字来过滤外设

// [central connectPeripheral:peripheral options:nil];

}

// 连接外设

// [central connectPeripheral:peripheral options:nil];

}

    6、连接外围设备

//连接外围设备,中心管理者连接外设成功,如果连接成功就会回调这个协议方法

/** 连接成功 */

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{

//连接成功之后,可以进行服务和特性的发现。 停止中心管理设备的扫描动作,要不然在你和已经连接好的外设进行数据沟通时,如果又有一个外设进行广播且符合你的连接条件,那么你的iOS设备也会去连接这个设备(因为iOS BLE4.0是支持一对多连接的),导致数据的混乱。

//停止扫描动作

[self.centralManager stopScan];

// 设置外设的代理

peripheral.delegate = self;

// 根据UUID来寻找服务

// [peripheral discoverServices:@[[CBUUID UUIDWithString:SERVICE_UUID]]];

//外设发现服务,传nil代表不过滤,一次性读出外设的所有服务

[peripheral discoverServices:nil];

NSLog(@"%s, line = %d, %@=连接成功", __FUNCTION__, __LINE__, peripheral.name);

}

//外设连接失败

/** 连接失败的回调 */

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {

NSLog(@"%s, line = %d, %@=连接失败", __FUNCTION__, __LINE__, peripheral.name);

}

//丢失连接 掉线

/** 断开连接 */

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {

NSLog(@"%s, line = %d, %@=断开连接", __FUNCTION__, __LINE__, peripheral.name);

// 断开连接可以设置重新连接

[central connectPeripheral:peripheral options:nil];

}

    7、获取外围设备服务和特征

/** 发现服务 */

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {

// 遍历出外设中所有的服务

for (CBService *service in peripheral.services) {

// NSLog(@"所有的服务:%@",service);

}

// 这里仅有一个服务,所以直接获取

CBService *service = peripheral.services.lastObject;

// 根据UUID寻找服务中的特征

// [peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:CHARACTERISTIC_UUID]] forService:service];

// [peripheral discoverCharacteristics:@[service.UUID] forService:service];

[peripheral discoverCharacteristics:nil forService:service];

}

    8、从外围设备读取数据

// 更新特征的value的时候会调用 (凡是从蓝牙传过来的数据都要经过这个回调,简单的说这个方法就是你拿数据的唯一方法) 你可以判断是否 从外围设备读数据

/** 接收到数据回调 */

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {

// if (characteristic == @"你要的特征的UUID或者是你已经找到的特征") {

// //characteristic.value就是你要的数据

// }

if ([peripheral.name hasPrefix:@"TEAMOSA"]){

NSData *data = characteristic.value;

NSString *value = [self hexadecimalString:data];

// NSLog(@"characteristic(读取到的): %@, data : %@, value : %@", characteristic, data, value);

}

// 拿到外设发送过来的数据

// NSData *data = characteristic.value;

// self.textFild.text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

}

    9、向外围设备发送(写入)数据

//这个方法你可以放在button的响应里面,也可以在找到特征的时候就写入,具体看你业务需求怎么用

//[self.peripherale writeValue:_batteryData forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];//第一个参数是已连接的蓝牙设备; 第二个参数是要写入到哪个特征; 第三个参数是通过此响应记录是否成功写入 需要注意的是特征的属性是否支持写数据

/** 写入数据回调 */

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error {

/*

typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {

CBCharacteristicPropertyBroadcast = 0x01,

CBCharacteristicPropertyRead = 0x02,

CBCharacteristicPropertyWriteWithoutResponse = 0x04,

CBCharacteristicPropertyWrite = 0x08,

CBCharacteristicPropertyNotify = 0x10,

CBCharacteristicPropertyIndicate = 0x20,

CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,

CBCharacteristicPropertyExtendedProperties = 0x80,

CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x100,

CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x200

};

打印出特征的权限(characteristic.properties),可以看到有很多种,这是一个NS_OPTIONS的枚举,可以是多个值

常见的又read,write,noitfy,indicate.知道这几个基本够用了,前俩是读写权限,后俩都是通知,俩不同的通知方式

*/

// NSLog(@"%s, line = %d, char.pro = %d", __FUNCTION__, __LINE__, characteristic.properties);

// 此时由于枚举属性是NS_OPTIONS,所以一个枚举可能对应多个类型,所以判断不能用 = ,而应该用包含

NSLog(@"write value success(写入成功) : %@", characteristic);

}

    10、具体调用给蓝牙外设写入数据方法,这里的例子是以按钮点击事件里面来调用处理

//发送按钮点击事件

- (void)sendClick {

if (!self.characteristic) {

return;

}

_tempValue = [NSString stringWithFormat:@"%.0f", progressView.centigradeDegree];

_timeValue = [NSString stringWithFormat:@"%.0ld", (long)progressView1.timeDegree];

NSString *ttData = [NSString stringWithFormat:@"%@,%@U", _tempValue, _timeValue];

// NSString *aaa = [DataCoverTool coverFromStringToHexStr:ttData];

// 用NSData类型来写入

// NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arry];

NSData *data = [ttData dataUsingEncoding:NSUTF8StringEncoding];

// NSData *data = [self dataWithString:ttData];

// 根据上面的特征self.characteristic来写入数据

[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];

如何使用Android蓝牙开发

Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输。本文档描述了怎样利用android平台提供的蓝牙API去实现蓝压设备之间的通信。蓝牙具有point-to-point 和 multipoint两种连接功能。

使用蓝牙API,可以做到:

* 搜索蓝牙设备

* 从本地的Bluetooth adapter中查询已经配对的设备

* 建立RFCOMM通道

* 通过service discovery连接到其它设备

* 在设备之间传输数据

* 管理多个连接

基础知识

本文档介绍了如何使用Android的蓝牙API来完成的四个必要的主要任务,使用蓝牙进行设备通信,主要包含四个部分:蓝牙设置、搜索设备(配对的或可见的)、连接、传输数据。

所有的蓝牙API在android.bluetooth包中。实现这些功能主要需要下面这几个类和接口:

BluetoothAdapter

代表本地蓝牙适配器(蓝牙发射器),是所有蓝牙交互的入口。通过它可以搜索其它蓝牙设备,查询已经配对的设备列表,通过已知的MAC地址创建BluetoothDevice,创建BluetoothServerSocket监听来自其它设备的通信。

BluetoothDevice

代表了一个远端的蓝牙设备, 使用它请求远端蓝牙设备连接或者获取 远端蓝牙设备的名称、地址、种类和绑定状态。 (其信息是封装在 bluetoothsocket 中) 。

BluetoothSocket

代表了一个蓝牙套接字的接口(类似于 tcp 中的套接字) ,他是应用程 序通过输入、输出流与其他蓝牙设备通信的连接点。

BluetoothServerSocket

代表打开服务连接来监听可能到来的连接请求 (属于 server 端) , 为了连接两个蓝牙设备必须有一个设备作为服务器打开一个服务套接字。 当远端设备发起连 接连接请求的时候,并且已经连接到了的时候,Blueboothserversocket 类将会返回一个 bluetoothsocket。

BluetoothClass

描述了一个设备的特性(profile)或该设备上的蓝牙大致可以提供哪些服务(service),但不可信。比如,设备是一个电话、计算机或手持设备;设备可以提供audio/telephony服务等。可以用它来进行一些UI上的提示。

BluetoothProfile

BluetoothHeadset

提供手机使用蓝牙耳机的支持。这既包括蓝牙耳机和免提(V1.5)模式。

BluetoothA2dp

定义高品质的音频,可以从一个设备传输到另一个蓝牙连接。 “A2DP的”代表高级音频分配模式。

BluetoothHealth

代表了医疗设备配置代理控制的蓝牙服务

BluetoothHealthCallback

一个抽象类,使用实现BluetoothHealth回调。你必须扩展这个类并实现回调方法接收更新应用程序的注册状态和蓝牙通道状态的变化。

BluetoothHealthAppConfiguration

代表一个应用程序的配置,蓝牙医疗第三方应用注册与远程蓝牙医疗设备交流。

BluetoothProfile.ServiceListener

当他们已经连接到或从服务断开时通知BluetoothProfile IPX的客户时一个接口(即运行一个特定的配置文件,内部服务)。

蓝牙权限

为了在你的应用中使用蓝牙功能,至少要在AndroidManifest.xml中声明两个权限:BLUETOOTH(任何蓝牙相关API都要使用这个权限) 和 BLUETOOTH_ADMIN(设备搜索、蓝牙设置等)。

为了执行蓝牙通信,例如连接请求,接收连接和传送数据都必须有BLUETOOTH权限。

必须要求BLUETOOTH_ADMIN的权限来启动设备发现或操纵蓝牙设置。大多数应用程序都需要这个权限能力,发现当地的蓝牙设备。此权限授予其他的能力不应该使用,除非应用程序是一个“电源管理”,将根据用户要求修改的蓝牙设置

注释:要请求BLUETOOTH_ADMIN的话,必须要先有BLUETOOTH。

在你的应用manifest 文件中声明蓝牙权限。例如:

manifest ...

uses-permission android:name="android.permission.BLUETOOTH" /

...

/manifest

通过查看uses-permission资料来声明应用权限获取更多的信息。

蓝牙设置

在你的应用通过蓝牙进行通信之前,你需要确认设备是否支持蓝牙,如果支持,确信它被打开。

如果不支持,则不能使用蓝牙功能。如果支持蓝牙,但不能够使用,你刚要在你的应用中请求使用蓝牙。这个要两步完成,使用BluetoothAdapter。

微信小程序蓝牙教程--完整版亲测

#使用mpvue 开发小程序过程中 简单介绍一下微信小程序蓝牙连接过程

#在蓝牙连接的过程中部分api需要加定时器延时1秒到2秒左右再执行,原因为何不知道,小程序有这样的要求

#1.首先是要初始化蓝牙:openBluetoothAdapter()

```js

if (wx.openBluetoothAdapter) {

wx.openBluetoothAdapter({

        success: function(res) {

            /* 获取本机的蓝牙状态 */

            setTimeout(() = {

                getBluetoothAdapterState()

            }, 1000)

        },

        fail: function(err) {

            // 初始化失败

        }

    })

    } else {    

    }

```

#2.检测本机蓝牙是否可用:

#  要在上述的初始化蓝牙成功之后回调里调用

```js

getBluetoothAdapterState() {

    var that= this;

    that.toastTitle= '检查蓝牙状态'

wx.getBluetoothAdapterState({

        success: function(res) {

startBluetoothDevicesDiscovery()

},

        fail(res) {

            console.log(res)

}

})

}

```

#3. 开始搜索蓝牙设备:

```js

startBluetoothDevicesDiscovery() {

    var that= this;

    setTimeout(() = {

wx.startBluetoothDevicesDiscovery({

            success: function(res) {

/* 获取蓝牙设备列表 */

                that.getBluetoothDevices()

},

            fail(res) {

}

})

}, 1000)

}

```

#4. 获取搜索到的蓝牙设备列表

# /* that.deviceName 是获取到的蓝牙设备的名称, 因为蓝牙设备在安卓和苹果手机上搜到的蓝牙地址显示是不一样的,所以根据设备名称匹配蓝牙*/

```js

getBluetoothDevices() {

    var that= this;

    setTimeout(() = {

wx.getBluetoothDevices({

            services: [],

            allowDuplicatesKey: false,

            interval: 0,

            success: function(res) {

                if (res.devices.length 0) {

                    if (JSON.stringify(res.devices).indexOf(that.deviceName) !== -1) {

                        for (let i = 0; i res.devices.length; i++) {

                            if (that.deviceName === res.devices[i].name) {

/* 根据指定的蓝牙设备名称匹配到deviceId */

                                that.deviceId = that.devices[i].deviceId;

                                setTimeout(() = {

                                    that.connectTO();

}, 2000);

};

};

} else {

}

} else {

}

},

            fail(res) {

                console.log(res, '获取蓝牙设备列表失败=====')

}

})

}, 2000)

},

```

#5.连接蓝牙

# 匹配到的蓝牙设备ID 发送连接蓝牙的请求, 连接成功之后 应该断开蓝牙搜索的api,然后去获取所连接蓝牙设备的service服务

```js

connectTO() {

wx.createBLEConnection({

        deviceId: deviceId,

        success: function(res) {

            that.connectedDeviceId = deviceId;

/* 4.获取连接设备的service服务 */

that.getBLEDeviceServices();

wx.stopBluetoothDevicesDiscovery({

                success: function(res) {

                    console.log(res, '停止搜索')

},

                fail(res) {

}

})

},

        fail: function(res) {

}

})

}

```

#6. 获取蓝牙设备的service服务,获取的serviceId有多个要试着连接最终确定哪个是稳定版本的service 获取服务完后获取设备特征值

```js

getBLEDeviceServices() {

    setTimeout(() = {

wx.getBLEDeviceServices({

            deviceId: that.connectedDeviceId,

            success: function(res) {

                that.services= res.services

/* 获取连接设备的所有特征值 */

that.getBLEDeviceCharacteristics()

},

            fail: (res) = {

}

})

}, 2000)

},

```

#7.获取蓝牙设备特征值

# 获取到的特征值有多个,最后要用的事能读,能写,能监听的那个值的uuid作为特征值id,

```js

getBLEDeviceCharacteristics() {

            setTimeout(() = {

wx.getBLEDeviceCharacteristics({

                    deviceId: connectedDeviceId,

                    serviceId: services[2].uuid,

                    success: function(res) {

                        for (var i = 0; i res.characteristics.length; i++) {

                            if ((res.characteristics[i].properties.notify || res.characteristics[i].properties.indicate)

                                (res.characteristics[i].properties.read res.characteristics[i].properties.write)) {

                                console.log(res.characteristics[i].uuid, '蓝牙特征值 ==========')

/* 获取蓝牙特征值 */

                                that.notifyCharacteristicsId = res.characteristics[i].uuid

// 启用低功耗蓝牙设备特征值变化时的 notify 功能

that.notifyBLECharacteristicValueChange()

}

}

},

                    fail: function(res) {

}

})

}, 1000)

},

```

#8.启动notify 蓝牙监听功能 然后使用 wx.onBLECharacteristicValueChange用来监听蓝牙设备传递数据

#接收到的数据和发送的数据必须是二级制数据, 页面展示的时候需要进行转换

```js

notifyBLECharacteristicValueChange() { // 启用低功耗蓝牙设备特征值变化时的 notify 功能

            var that= this;

            console.log('6.启用低功耗蓝牙设备特征值变化时的 notify 功能')

wx.notifyBLECharacteristicValueChange({

                state: true,

                deviceId: that.connectedDeviceId,

                serviceId: that.notifyServicweId,

                characteristicId: that.notifyCharacteristicsId,

                complete(res) {

/*用来监听手机蓝牙设备的数据变化*/

wx.onBLECharacteristicValueChange(function(res) {

/**/

                        that.balanceData += that.buf2string(res.value)

                        that.hexstr += that.receiveData(res.value)

})

},

                fail(res) {

                    console.log(res, '启用低功耗蓝牙设备监听失败')

                    that.measuringTip(res)

}

})

},

/*转换成需要的格式*/

buf2string(buffer) {

                    var arr = Array.prototype.map.call(new Uint8Array(buffer), x = x)

                    return arr.map((char, i) = {

                        return String.fromCharCode(char);

                    }).join('');

},

receiveData(buf) {

return this.hexCharCodeToStr(this.ab2hex(buf))

},

/*转成二进制*/

ab2hex (buffer) {

              var hexArr = Array.prototype.map.call(

                  new Uint8Array(buffer), function (bit) {

                      return ('00' + bit.toString(16)).slice(-2)

}

)

              return hexArr.join('')

},

/*转成可展会的文字*/

hexCharCodeToStr(hexCharCodeStr) {

              var trimedStr = hexCharCodeStr.trim();

              var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;

              var len = rawStr.length;

              var curCharCode;

              var resultStr= [];

              for (var i = 0; i len; i = i+ 2) {

                  curCharCode = parseInt(rawStr.substr(i, 2), 16);

                  resultStr.push(String.fromCharCode(curCharCode));

}

              return resultStr.join('');

},

```

# 向蓝牙设备发送数据

```js

sendData(str) {

    let that= this;

    let dataBuffer = new ArrayBuffer(str.length)

    let dataView = new DataView(dataBuffer)

    for (var i = 0; i str.length; i++) {

        dataView.setUint8(i, str.charAt(i).charCodeAt())

}

    let dataHex = that.ab2hex(dataBuffer);

    this.writeDatas = that.hexCharCodeToStr(dataHex);

wx.writeBLECharacteristicValue({

        deviceId: that.connectedDeviceId,

        serviceId: that.notifyServicweId,

        characteristicId: that.notifyCharacteristicsId,

        value: dataBuffer,

        success: function (res) {

            console.log('发送的数据:' + that.writeDatas)

            console.log('message发送成功')

},

        fail: function (res) {

},

        complete: function (res) {

}

})

},

```

# 当不需要连接蓝牙了后就要关闭蓝牙,并关闭蓝牙模块

```js

// 断开设备连接

closeConnect() {

if (that.connectedDeviceId) {

wx.closeBLEConnection({

            deviceId: that.connectedDeviceId,

            success: function(res) {

that.closeBluetoothAdapter()

},

            fail(res) {

}

})

} else {

that.closeBluetoothAdapter()

}

},

// 关闭蓝牙模块

closeBluetoothAdapter() {

wx.closeBluetoothAdapter({

        success: function(res) {

},

        fail: function(err) {

}

})

},

```

#在向蓝牙设备传递数据和接收数据的过程中,并未使用到read的API 不知道有没有潜在的问题,目前线上运行为发现任何的问题

#今天的蓝牙使用心得到此结束,谢谢

android蓝牙开发,PC端模拟串口接收字符,该如何编程?

您好,android蓝牙这方面还是很好搞的,因为大家的方式都是差不多的。先说说如何开启蓝牙设备和设置可见时间:

private void search() {

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

if (!adapter.isEnabled()) {

adapter.enable();

}

Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600); //3600为蓝牙设备可见时间

startActivity(enable);

Intent searchIntent = new Intent(this, ComminuteActivity.class);

startActivity(searchIntent);

}

首先,需要获得一个BluetoothAdapter,可以通过getDefaultAdapter()获得系统默认的蓝牙适配器,当然我们也可以自己指定,但这个真心没有必要,至少我是不需要的。然后我们检查手机的蓝牙是否打开,如果没有,通过enable()方法打开。接着我们再设置手机蓝牙设备的可见,可见时间可以自定义。

完成这些必要的设置后,我们就可以正式开始与蓝牙模块进行通信了:

public class ComminuteActivity extends Activity {

private BluetoothReceiver receiver;

private BluetoothAdapter bluetoothAdapter;

private ListString devices;

private ListBluetoothDevice deviceList;

private Bluetooth client;

private final String lockName = "BOLUTEK";

private String message = "000001";

private ListView listView;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.search_layout);

listView = (ListView) this.findViewById(R.id.list);

deviceList = new ArrayListBluetoothDevice();

devices = new ArrayListString();

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

bluetoothAdapter.startDiscovery();

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

receiver = new BluetoothReceiver();

registerReceiver(receiver, filter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView? parent, View view, int position, long id) {

setContentView(R.layout.connect_layout);

BluetoothDevice device = deviceList.get(position);

client = new Bluetooth(device, handler);

try {

client.connect(message);

} catch (Exception e) {

Log.e("TAG", e.toString());

}

}

});

}

@Override

protected void onDestroy() {

unregisterReceiver(receiver);

super.onDestroy();

}

private final Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

switch (msg.what) {

case Bluetooth.CONNECT_FAILED:

Toast.makeText(ComminuteActivity.this, "连接失败", Toast.LENGTH_LONG).show();

try {

client.connect(message);

} catch (Exception e) {

Log.e("TAG", e.toString());

}

break;

case Bluetooth.CONNECT_SUCCESS:

Toast.makeText(ComminuteActivity.this, "连接成功", Toast.LENGTH_LONG).show();

break;

case Bluetooth.READ_FAILED:

Toast.makeText(ComminuteActivity.this, "读取失败", Toast.LENGTH_LONG).show();

break;

case Bluetooth.WRITE_FAILED:

Toast.makeText(ComminuteActivity.this, "写入失败", Toast.LENGTH_LONG).show();

break;

case Bluetooth.DATA:

Toast.makeText(ComminuteActivity.this, msg.arg1 + "", Toast.LENGTH_LONG).show();

break;

}

}

};

private class BluetoothReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

if (BluetoothDevice.ACTION_FOUND.equals(action)) {

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

if (isLock(device)) {

devices.add(device.getName());

}

deviceList.add(device);

}

showDevices();

}

}

private boolean isLock(BluetoothDevice device) {

boolean isLockName = (device.getName()).equals(lockName);

boolean isSingleDevice = devices.indexOf(device.getName()) == -1;

return isLockName isSingleDevice;

}

private void showDevices() {

ArrayAdapterString adapter = new ArrayAdapterString(this, android.R.layout.simple_list_item_1,

devices);

listView.setAdapter(adapter);

}

}

蓝牙app开发教程的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于蓝牙通信app设计及程序、蓝牙app开发教程的信息别忘了在本站进行查找喔。

扫码二维码