手机蓝牙app开发教程(蓝牙应用开发)

软件开发 3037
今天给各位分享手机蓝牙app开发教程的知识,其中也会对蓝牙应用开发进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!如何使用Android蓝牙开发 Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输。本文档描述了怎样利用android平台提供的蓝牙API去实现蓝压设备之间的通信。蓝牙具有point-to-point 和 multipoint两种连接功能。使用蓝牙API,可以做到:

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

如何使用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开发教程的信息别忘了在本站进行查找喔。

扫码二维码