手机蓝牙app开发教程过程(安卓蓝牙开发流程)
今天给各位分享手机蓝牙app开发教程过程的知识,其中也会对安卓蓝牙开发流程进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
- 1、android蓝牙开发,PC端模拟串口接收字符,该如何编程?
- 2、微信小程序蓝牙模块开发
- 3、如何开发简单的调试蓝牙app
- 4、如何使用Android蓝牙开发
- 5、求教如何制作一个安卓手机蓝牙制作的app程序,用于和单片机上的蓝牙模块,实现数据的传送
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);
}
}
微信小程序蓝牙模块开发
//index.js
//获取应用实例
const app = getApp()
const util = require('../../utils/util.js')
const bletool = require('../../utils/bletool.js')
Page({
data: {
// lists: [{ 'order_no': '1111', 'car_no': '321', 'car_type': '尚好捷', 'order_date': '2018-01-02 08:00', 'order_money': '16.00', 'order_time': '4' }],
car_no: '',
order_no: '',
lists: [],
bleList: [], //蓝牙设备数组
serviceId: '',//592B3370-3900-9A71-4535-35D4212D2837
serviceMac: '',//C9:9B:4C:E7:DE:10
service_psd: '',//855525B837253705595800000329
service_uuid: '',
deviceId:'',
characteristics:[] //特征值
},
onLoad: function (options) {
this.initBle();
},
onReady: function () {
// 页面渲染完成
},
onShow: function () {
if (app.globalData.car_no.length0){
this.getDeviceInfo();
}
},
onHide: function () {
// 页面隐藏
},
onUnload: function () {
// 页面关闭
app.globalData.car_no=''
},
//蓝牙相关
//初始化蓝牙
initBle: function () {
var that = this;
wx.onBluetoothAdapterStateChange(function (res) {
console.log('adapterState changed, now is', res)
app.globalData.ble_state = res.available;
if (res.available) {
that.initBle();
} else {
util.showToast('手机蓝牙已关闭');
app.globalData.ble_isonnectting = false;
}
})
//打开蓝牙适配器
wx.openBluetoothAdapter({
success: function (res) {
console.log('打开蓝牙适配器成功');
that.getBluetoothAdapterState();
app.globalData.ble_state = true;
that.onBluetoothDeviceFound();
},
fail: function (res) {
// fail
console.log(res)
util.showToast('请打开手机蓝牙');
},
complete: function (res) {
// complete
}
})
},
onBluetoothDeviceFound:function(){
var that = this;
//监听扫描
wx.onBluetoothDeviceFound(function (res) {
// res电脑模拟器返回的为数组;手机返回的为蓝牙设备对象
console.log('监听搜索新设备:', res);
that.updateBleList([res])
})
},
getBluetoothAdapterState: function () {
var that = this;
wx.getBluetoothAdapterState({
success: function (res) {
var available = res.available;
var discovering = res.discovering;
if (!available) {
util.showToast('蓝牙不可用');
} else {
if (!discovering) {
// that.startBluetoothDevicesDiscovery();
}
}
}
})
},
startBluetoothDevicesDiscovery: function () {
var that = this;
var services = [];
services.push(this.data.serviceId);
wx.showLoading({
title: '设备搜索中'
});
setTimeout(function () {
wx.hideLoading();
if (app.globalData.deviceId.length==0){
util.showModal('设备搜索失败,请重试');
}
}, 10000)
if(bletool.isIOS()){
wx.startBluetoothDevicesDiscovery({
services: services,
allowDuplicatesKey: true,
success: function (res) {
console.log('ios搜索成功');
console.log(res);
},
fail: function (err) {
console.log(err);
}
});
}else{
wx.startBluetoothDevicesDiscovery({
// services: services,
allowDuplicatesKey: true,
success: function (res) {
console.log('Android搜索成功');
console.log(res);
},
fail: function (err) {
console.log(err);
wx.hideLoading();
that.startBluetoothDevicesDiscovery();
// that.getBluetoothAdapterState();
util.showToast('搜索失败');
}
});
}
},
startConnectDevices: function (ltype, array) {
var that = this;
clearTimeout(that.getConnectedTimer);
that.getConnectedTimer = null;
wx.stopBluetoothDevicesDiscovery({
success: function (res) {
// success
}
})
app.globalData.ble_isonnectting = true;
console.log('连接前:'+that.deviceId);
wx.createBLEConnection({
deviceId: that.deviceId,
success: function (res) {
if (res.errCode == 0) {
console.log('连接成功:');
that.getService(that.deviceId);
}
},
fail: function (err) {
console.log('连接失败:', err);
wx.hideLoading();
util.showModal('设备连接失败,请重试');
// if (ltype == 'loop') {
// that.connectDeviceIndex += 1;
// that.loopConnect(array);
// } else {
// that.startBluetoothDevicesDiscovery();
// that.getConnectedBluetoothDevices();
// }
app.globalData.ble_isonnectting = false;
},
complete: function () {
}
});
},
getService: function (deviceId) {
var that = this;
// 监听蓝牙连接
wx.onBLEConnectionStateChange(function (res) {
console.log(res);
app.globalData.ble_isonnectting = res.connected
if (!res.connected) {
util.showToast('连接断开');
}
});
// 获取蓝牙设备service值
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function (res) {
console.log('获取蓝牙设备service值');
console.log(res);
that.getCharacter(deviceId, res.services);
}
})
},
getCharacter: function (deviceId, services) {
var that = this;
services.forEach(function (value, index, array) {
if (value.isPrimary) {
that.setData({
service_uuid: value.uuid,
deviceId: deviceId
})
app.globalData.service_uuid= value.uuid;
app.globalData.deviceId=deviceId;
}
});
//监听通知
wx.onBLECharacteristicValueChange(function (res) {
// callback
console.log('value change', res)
const hex = bletool.buf2char(res.value)
console.log('返回的数据:', hex)
//配对密码
if (hex.indexOf('855800000106') != -1) {
wx.hideLoading();
var charact_write = that.data.characteristics[1]
bletool.writeDataToDevice(that.data.deviceId, that.data.service_uuid, charact_write, that.data.service_psd);
wx.showToast({
title: '设备已连接',
icon: 'success',
duration: 3000
})
setTimeout(function () {
bletool.writeDataToDevice(that.data.deviceId, that.data.service_uuid, charact_write, '235525B837253705590400000273');
}, 2000)
} else if (hex.indexOf('23040000') != -1) {
//启动成功
that.starRenting();
}
})
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: that.getServiceUUID(),
success: function (res) {
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: that.getServiceUUID(),
success: function (res) {
console.log('特征', res)
that.setData({
characteristics:res.characteristics
})
app.globalData.characteristics = res.characteristics;
var charact_read = res.characteristics[0]
},
loopConnect: function (devicesId) {
var that = this;
var listLen = devicesId.length;
if (devicesId[this.connectDeviceIndex]) {
this.deviceId = devicesId[this.connectDeviceIndex];
this.startConnectDevices('loop', devicesId);
} else {
console.log('已配对的设备小程序蓝牙连接失败');
that.startBluetoothDevicesDiscovery();
that.getConnectedBluetoothDevices();
}
},
//更新数据 devices为数组类型
updateBleList: function (devices) {
console.log('设备数据:',devices);
var newData = this.data.bleList
var that = this
var tempDevice = null;
for (var i = 0; i devices.length; i++) {
//ios设备
if (devices[i].devices != null) {
if (devices[i].devices.length 0) {
tempDevice = devices[i].devices[0];
}
else {
continue
}
}
//安卓
else {
tempDevice = devices[i];
}
if (!this.isExist(tempDevice)) {
newData.push(tempDevice)
}
}
console.log('数据:');
console.log(newData)
this.setData({
bleList: newData
})
if (!app.globalData.ble_isonnectting) {
var that = this;
this.data.bleList.forEach(function (value, index, array) {
//找到对应id的设备,ios判断服务id安卓判断mac地址
var deviceId = value['deviceId'];
if(bletool.isIOS()){
let advertisServiceUUID = value['advertisServiceUUIDs'][0];
if (advertisServiceUUID == that.data.serviceId.toUpperCase()){
that.deviceId = deviceId;
console.log(that.deviceId);
that.startConnectDevices();
}
}else{
if (deviceId == that.data.serviceMac) {
that.deviceId = deviceId;
console.log(that.deviceId);
that.startConnectDevices();
}
}
});
}
},
//是否已存在 存在返回true 否则false
isExist: function (device) {
var tempData = this.data.bleList
for (var i = 0; i tempData.length; i++) {
if (tempData[i].deviceId == device.deviceId) {
return true
}
}
return false
},
//服务uuid
getServiceUUID: function () {
return bletool.stringTransition(this.data.service_uuid);
},
getDeviceInfo: function () {
let car_no = app.globalData.car_no;
var that = this;
wx.request({
url: app.globalData.serverURL + '?c=cara=getDeviceInfoopen_id=' + app.globalData.open_id + 'car_no=' + car_no,
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: { 'content-type': 'application/json' }, // 设置请求的 header
success: function (res) {
// success
var data = res.data;
console.log(data);
if (data.result == 1) {
app.globalData.serviceId = data.data.service_id;
app.globalData.serviceMac = data.data.service_mac,
app.globalData.service_psd = '85' + data.data.service_psd + '5800000329';
that.setData({
serviceId: data.data.service_id,
serviceMac: data.data.service_mac,
service_psd: '85' + data.data.service_psd+'5800000329',
})
app.startBluetoothDevicesDiscovery();
// that.onBLECharacteristicValueChange();
} else {
util.showModal(data.msg);
}
},
fail: function () {
},
complete: function () {
// complete
}
});
},
})
如何开发简单的调试蓝牙app
分两种情况:
你懂技术,安卓JAVA或苹果OC。有一定的技术基础,并且愿意去学习和尝试,简单的蓝牙app其实真的简单,就是通过蓝牙协议进行软硬件联调,指令也就那几条,只要调通就好了。
不懂技术。那就百度一家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。
求教如何制作一个安卓手机蓝牙制作的app程序,用于和单片机上的蓝牙模块,实现数据的传送
下位机,用串口和蓝牙模块连接,通信
上位机,安卓app开发用eclipse或者是android studio,蓝牙有相关的函数,,连接,断开,接受,网上大部分代码套着用就行了,,如果需要修改也修改的不多,,主ui界面的时候,不能有进程的占用和其他的一些的线程的操作,所以就得到子线程里面去执行了,还是先学学基础吧,之后再看这些的话,就容易的多了
手机蓝牙app开发教程过程的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于安卓蓝牙开发流程、手机蓝牙app开发教程过程的信息别忘了在本站进行查找喔。