导航:首页 > 操作系统 > androidble蓝牙开发

androidble蓝牙开发

发布时间:2022-06-20 03:07:29

android ble开发 怎么在后台 进入ble范围自动提醒

目前在开发android
ble
方面,想要实现程序在后台运行,进入ble设备范围就给用户发送通知。我是通过把connectGatt(Context
context,
boolean
autoConnect,
BluetoothGattCallback
callback)
的自动连接参数设成true来判断

❷ android蓝牙程序开发中,如何确定一台手机当前是服务器还是客户端

首先,要操作蓝牙,先要在AndroidManifest.xml里加入权限

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

<uses-permissionandroid:name="android.permission.BLUETOOTH" />
然后,看下api,Android所有关于蓝牙开发的类都在android.bluetooth包下。 而需要用到了就只有几个而已:
1.BluetoothAdapter 顾名思义,蓝牙适配器,直到我们建立bluetoothSocket连接之前,都要不断操作它BluetoothAdapter里的方法很多,常用的有以下几个:cancelDiscovery() 根据字面意思,是取消发现,也就是说正在搜索设备的时候调用这个方法将不再继续搜索disable()关闭蓝牙enable()打开蓝牙,这个方法打开蓝牙不会弹出提示,更多的时候需要问下用户是否打开,一下这两行代码同样是打开蓝牙,不过会提示用户:Intemtenabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enabler,reCode);//同startActivity(enabler);

getAddress()获取本地蓝牙地址getDefaultAdapter()获取默认BluetoothAdapter,实际上,也只有这一种方法获取BluetoothAdaptergetName()获取本地蓝牙名称getRemoteDevice(String address)根据蓝牙地址获取远程蓝牙设备getState()获取本地蓝牙适配器当前状态(感觉可能调试的时候更需要)isDiscovering()判断当前是否正在查找设备,是返回true***isEnabled()判断蓝牙是否打开,已打开返回true,否则,返回false***(String name,UUID uuid)根据名称,UUID创建并返回BluetoothServerSocket,这是创建BluetoothSocket服务器端的第一步startDiscovery()开始搜索,这是搜索的第一步。 2.BluetoothDevice看名字就知道,这个类描述了一个蓝牙设备(UUIDuuid)根据UUID创建并返回一个BluetoothSocket这个方法也是我们获取BluetoothDevice的目的——创建BluetoothSocket
这个类其他的方法,如getAddress(),getName(),同BluetoothAdapter;

3.BluetoothServerSocket如果去除了Bluetooth相信大家一定再熟悉不过了,既然是Socket,方法就应该都差不多,这个类一种只有三个方法
两个重载的accept(),accept(inttimeout)两者的区别在于后面的方法指定了过时时间,需要注意的是,执行这两个方法的时候,直到接收到了客户端的请求(或是过期之后),都会阻塞线程,应该放在新线程里运行。

还有一点需要注意的是,这两个方法都返回一个BluetoothSocket,最后的连接也是服务器端与客户端的两个BluetoothSocket的连接。

4.BluetoothSocket,跟BluetoothServerSocket相对,是客户端一共5个方法,不出意外,都会用到close(),关闭connect()连接getInptuStream()获取输入流getOutputStream()获取输出流getRemoteDevice()获取远程设备,这里指的是获取bluetoothSocket指定连接的那个远程蓝牙设备 。

❸ Android ble 接收数据

由于最近学校组织了一个移动APP(安卓)设计大赛,自己也学习安卓有一段时间了,就跟同学商量一起去参加试试,一拍即合,然后我们就开始想idea,因为最近可穿戴设备比较火,我们也就想试试。经过商量,我负责Android上位机的开发,同学负责下位机的开发。

上位机的开发主要是低功耗蓝牙BLE的开发,然后就开始找资料,各种找,最后谷歌官方提供的demo还有其他网友基于官方demo修改的demo,结合网上的博客对demo进行理解。刚开始是觉得看起来有点费劲,各种广播,跳来跳去的,刚开始就晕菜了。但是经过三四天的理解,算是把官方的demo理解了。

代码基本上都是官方的demo,只是通过修改获得自己想要的结果,下面就简单介绍一下自己的理解。

一、扫描BLE设备activity

检查该设备是否支持BLE设备,谷歌在Android4.3才开始支持BLE设备(晕死,很长一段时间都没有一台4.3的设备,看着程序修改了也不能测试!)。

详细

❹ android 蓝牙ble开发锁屏状态下不能扫描么

Android 从 4.3(API Level 18) 开始支持低功耗蓝牙,但是只支持作为中心设备(Central)模式,这就意味着 Android 设备只能主动扫描和链接其他外围设备(Peripheral)。从 Android 5.0(API Level 21) 开始两种模式都支持。BLE 官方文档在 这里。
在 BluetoothAdapter.startLeScan() 的时候,在 BluetoothAdapter.LeScanCallback.onLeScan() 中不能做太多事情,特别是周围的BLE设备多的时候,非常容易导致出现如下错误:
E/GKI_LINUX(17741): ##### ERROR : GKI_exception: GKI_exception(): Task State Table
E/GKI_LINUX(17741): #####
E/GKI_LINUX(17741): ##### ERROR : GKI_exception: TASK ID [0] task name [BTU] state [1]
E/GKI_LINUX(17741): #####
E/GKI_LINUX(17741): ##### ERROR : GKI_exception: TASK ID [1] task name [BTIF] state [1]
E/GKI_LINUX(17741): #####
E/GKI_LINUX(17741): ##### ERROR : GKI_exception: TASK ID [2] task name [A2DP-MEDIA] state [1]
E/GKI_LINUX(17741): #####
E/GKI_LINUX(17741): ##### ERROR : GKI_exception: GKI_exception 65524 getbuf: out of buffers#####
E/GKI_LINUX(17741): ##### ERROR : GKI_exception:
E/GKI_LINUX(17741): **
开发建议:在 onLeScan() 回调中只做尽量少的工作,可以把扫描到的设备,扔到另外一个线程中去处理,让 onLeScan() 尽快返回。

❺ 安卓蓝牙遥控器属于ble开发吗

是属于这个范畴里面的,BLE 即 Bluetooth Low Energy,蓝牙低功耗技术,是蓝牙4.0引入的新技术。现在越来越多的智能设备使用了BLE,像满大街的安瑞创智能遥控器AN1201C就是应用这种技术。

❻ android 蓝牙BLE 该怎么搞,我是想搞个中心和周边 ,推送消息

Android4.3 规范了BLE的API,但是直到目前的4.4,还有些功能不完善。

在BLE协议中,有两个角色,周边(Periphery)和中央(Central);周边是数据提供者,中央是数据使用/处理者;在iOS SDK里面,可以把一个iOS设备作为一个周边,也可以作为一个中央;但是在Android SDK里面,直到目前最新的Android4.4.2,Android手机只能作为中央来使用和处理数据;那数据从哪儿来?从BLE设备来,现在的很多可穿戴设备都是用BLE来提供数据的。

一个中央可以同时连接多个周边,但是一个周边某一时刻只能连接一个中央。

大概了解了概念后,看看Android BLE SDK的四个关键类(class):

a)BluetoothGattServer作为周边来提供数据;BluetoothGattServerCallback返回周边的状态。

b)BluetoothGatt作为中央来使用和处理数据;BluetoothGattCallback返回中央的状态和周边提供的数据。

因为我们讨论的是Android的BLE SDK,下面所有的BluetoothGattServer代表周边,BluetoothGatt代表中央。


一.创建一个周边(虽然目前周边API在Android手机上不工作,但还是看看)

a)先看看周边用到的class,蓝色椭圆

❼ Android 蓝牙开发,求解如何代码实现让本机与其他设备进行连接未配对的先配对,已配对的直接连接.

我在github有写过一个例子:https://github.com/TitleZWC/BLEDemo
希望对你有帮助

❽ android蓝牙ble4.0开发共享失败怎么办

2.1首先获取BluetoothManager

复制代码 代码如下:
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

2.2获取BluetoothAdapter

复制代码 代码如下:
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();

2.3创建BluetoothAdapter.LeScanCallback
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

@Override
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {

runOnUiThread(new Runnable() {
@Override
public void run() {
try {
String struuid = NumberUtils.bytes2HexString(NumberUtils.reverseBytes(scanRecord)).replace("-", "").toLowerCase();
if (device!=null && struuid.contains(DEVICE_UUID_PREFIX.toLowerCase())) {
mBluetoothDevices.add(device);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};

2.4.开始搜索设备。

复制代码 代码如下:
mBluetoothAdapter.startLeScan(mLeScanCallback);

2.5.BluetoothDevice 描述了一个蓝牙设备 提供了getAddress()设备Mac地址,getName()设备的名称。
2.6开始连接设备
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* @param address
* The device address of the destination device.
*
* @return Return true if the connection is initiated successfully. The
* connection result is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}

// Previously connected device. Try to reconnect. (先前连接的设备。 尝试重新连接)
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}

final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the
// autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}

2.7连接到设备之后获取设备的服务(Service)和服务对应的Characteristic。

// Demonstrates how to iterate through the supported GATT
// Services/Characteristics.
// In this sample, we populate the data structure that is bound to the
// ExpandableListView
// on the UI.
private void displayGattServices(List<BluetoothGattService> gattServices) {
if (gattServices == null)
return;
String uuid = null;
ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<>();
ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<>();

mGattCharacteristics = new ArrayList<>();

// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
HashMap<String, String> currentServiceData = new HashMap<>();
uuid = gattService.getUuid().toString();
if (uuid.contains("ba11f08c-5f14-0b0d-1080")) {//服务的uuid
//System.out.println("this gattService UUID is:" + gattService.getUuid().toString());
currentServiceData.put(LIST_NAME, "Service_OX100");
currentServiceData.put(LIST_UUID, uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<>();
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<>();

// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap<>();
uuid = gattCharacteristic.getUuid().toString();
if (uuid.toLowerCase().contains("cd01")) {
currentCharaData.put(LIST_NAME, "cd01");
} else if (uuid.toLowerCase().contains("cd02")) {
currentCharaData.put(LIST_NAME, "cd02");
} else if (uuid.toLowerCase().contains("cd03")) {
currentCharaData.put(LIST_NAME, "cd03");
} else if (uuid.toLowerCase().contains("cd04")) {
currentCharaData.put(LIST_NAME, "cd04");
} else {
currentCharaData.put(LIST_NAME, "write");
}

currentCharaData.put(LIST_UUID, uuid);
gattCharacteristicGroupData.add(currentCharaData);
}

mGattCharacteristics.add(charas);

gattCharacteristicData.add(gattCharacteristicGroupData);

mCharacteristicCD01 = gattService.getCharacteristic(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD02 = gattService.getCharacteristic(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD03 = gattService.getCharacteristic(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"));
mCharacteristicCD04 = gattService.getCharacteristic(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"));
mCharacteristicWrite = gattService.getCharacteristic(UUID.fromString("0000cd20-0000-1000-8000-00805f9b34fb"));

//System.out.println("=======================Set Notification==========================");
// 开始顺序监听,第一个:CD01
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD01, true);
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD02, true);
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD03, true);
mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD04, true);
}
}
}

2.8获取到特征之后,找到服务中可以向下位机写指令的特征,向该特征写入指令。
public void wirteCharacteristic(BluetoothGattCharacteristic characteristic) {

if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}

mBluetoothGatt.writeCharacteristic(characteristic);

}

2.9写入成功之后,开始读取设备返回来的数据。

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
//System.out.println("=======status:" + status);
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices());

} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}

@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
//从特征中读取数据
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//System.out.println("onCharacteristicRead");
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
//向特征中写入数据
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//System.out.println("--------write success----- status:" + status);
}

/*
* when connected successfully will callback this method this method can
* dealwith send password or data analyze

*当连接成功将回调该方法
*/
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
if (characteristic.getValue() != null) {

//System.out.println(characteristic.getStringValue(0));
}
//System.out.println("--------onCharacteristicChanged-----");
}

@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {

//System.out.println(" = " + status + ", descriptor =" + descriptor.getUuid().toString());

UUID uuid = descriptor.getCharacteristic().getUuid();
if (uuid.equals(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD01NOTIDIED);
} else if (uuid.equals(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD02NOTIDIED);
} else if (uuid.equals(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD03NOTIDIED);
} else if (uuid.equals(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"))) {
broadcastUpdate(ACTION_CD04NOTIDIED);
}
}

@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
//System.out.println("rssi = " + rssi);
}
};

----------------------------------------------
//从特征中读取数据
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
//System.out.println("onCharacteristicRead");
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}

❾ android api14怎么开发ble

通过BLE连接,读写属性类小数据的Profile通用规范。现在所有的BLE应用Profile都是基于GATT的。

Attribute Protocol (ATT)

GATT是基于ATT Protocol的。ATT针对BLE设备做了专门的优化,具体就是在传输过程中使用尽量少的数据。
每个属性都有一个唯一的UUID,属性将以characteristics and services的形式传输。

Characteristic
Characteristic可以理解为一个数据类型,它包括一个value和0至多个对次value的描述(Descriptor)。

Descriptor
对Characteristic的描述,例如范围、计量单位等。

Service
Characteristic的集合。例如一个service叫做“Heart Rate Monitor”,
它可能包含多个Characteristics,其中可能包含一个叫做“heart rate measurement"的Characteristic。

二、角色和职责:
Android设备与BLE设备交互有两组角色:

中心设备和外围设备(Central vs. peripheral);
GATT server vs. GATT client.

Central vs. peripheral:
中心设备和外围设备的概念针对的是BLE连接本身。
Central角色负责scan advertisement。而peripheral角色负责make advertisement。

GATT server vs. GATT client:
这两种角色取决于BLE连接成功后,两个设备间通信的方式。

举例说明:
现有一个活动追踪的BLE设备和一个支持BLE的Android设备。
Android设备支持Central角色,而BLE设备支持peripheral角色。
创建一个BLE连接需要这两个角色都存在,都仅支持Central角色或者都仅支持peripheral角色则无法建立连接。

当连接建立后,它们之间就需要传输GATT数据。
谁做server,谁做client,则取决于具体数据传输的情况。
例如,如果活动追踪的BLE设备需要向Android设备传输sensor数据,则活动追踪器自然成为了server端;
而如果活动追踪器需要从Android设备获取更新信息,则Android设备作为server端可能更合适。
三、权限及feature:

和经典蓝牙一样,应用使用蓝牙,需要声明BLUETOOTH权限,
如果需要扫描设备或者操作蓝牙设置,则还需要BLUETOOTH_ADMIN权限:
```java
<uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

```
除了蓝牙权限外,如果需要BLE feature则还需要声明uses-feature:
```java
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

```
按时required为true时,则应用只能在支持BLE的Android设备上安装运行;
required为false时,Android设备均可正常安装运行,需要在代码运行时判断设备是否支持BLE feature:
```java
// Use this check to determine whether BLE is supported on the device. Then// you can selectively disable BLE-related features.if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); finish();}

阅读全文

与androidble蓝牙开发相关的资料

热点内容
服务器世界第一是什么公司的 浏览:19
精通编程入门 浏览:16
99单片机原理 浏览:61
linuxssh互信 浏览:288
支持128加密的浏览器 浏览:292
程序员下载器 浏览:48
退出云服务器代码 浏览:900
军状如命令 浏览:263
如何安卓系统更新 浏览:74
linux命令在哪里输入 浏览:497
编程语言集合类怎么选 浏览:93
如何将pdf转化为word 浏览:11
迈克菲隔离区解压密码 浏览:785
怎么用伟福编译 浏览:867
计算机算法专家 浏览:501
什么app清理垃圾 浏览:643
android流媒体服务器 浏览:183
各种算法的时间复杂度是指 浏览:116
帮助高考生缓解压力 浏览:850
自媒体聚合APP需要什么资质 浏览:487