当前位置:首页 » 安卓系统 » android蓝牙40开发

android蓝牙40开发

发布时间: 2022-08-09 01:15:58

⑴ 如何实现Android蓝牙开发 自动配对连接,并不弹出提示框

实现android蓝牙开发 自动配对连接,并不弹出提示框: 源码 BluetoothDevice 类中还有两个隐藏方法:cancelBondProcess()和cancelPairingUserInput(),这两个方法一个是取消配对进程一个是取消用户输入 下面是自动配对的代码 Mainfest,xml注册 <receiver android:name="." > <intent-filter> <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" /> </intent-filter> </receiver> 自己在收到广播时处理并将预先输入的密码设置进去 public class extends BroadcastReceiver { String strPsw = "0"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if (intent.getAction().equals( "android.bluetooth.device.action.PAIRING_REQUEST")) { BluetoothDevice btDevice = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234"); // device.setPin(pinBytes); Log.i("tag11111", "ddd"); try { ClsUtils.setPin(btDevice.getClass(), btDevice, strPsw); // 手机和蓝牙采集器配对 ClsUtils.createBond(btDevice.getClass(), btDevice); ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } <b>/************************************ 蓝牙配对函数 * **************/ import java.lang.reflect.Field; import java.lang.reflect.Method; import android.bluetooth.BluetoothDevice; import android.util.Log; public class ClsUtils { /** * 与设备配对 参考源码:platform/packages/apps/Settings.git * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java */ static public boolean createBond(Class btClass, BluetoothDevice btDevice) throws Exception { Method createBondMethod = btClass.getMethod("createBond"); Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice); return returnValue.booleanValue(); } /** * 与设备解除配对 参考源码:platform/packages/apps/Settings.git * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java */ static public boolean removeBond(Class btClass, BluetoothDevice btDevice) throws Exception { Method removeBondMethod = btClass.getMethod("removeBond"); Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice); return returnValue.booleanValue(); } static public boolean setPin(Class btClass, BluetoothDevice btDevice, String str) throws Exception { try { Method removeBondMethod = btClass.getDeclaredMethod("setPin", new Class[] {byte[].class}); Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice, new Object[] {str.getBytes()}); Log.e("returnValue", "" + returnValue); } catch (SecurityException e) { // throw new RuntimeException(e.getMessage()); e.printStackTrace(); } catch (IllegalArgumentException e) { // throw new RuntimeException(e.getMessage()); e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } // 取消用户输入 static public boolean cancelPairingUserInput(Class btClass, BluetoothDevice device) throws Exception { Method createBondMethod = btClass.getMethod("cancelPairingUserInput"); // cancelBondProcess() Boolean returnValue = (Boolean) createBondMethod.invoke(device); return returnValue.booleanValue(); } // 取消配对 static public boolean cancelBondProcess(Class btClass, BluetoothDevice device) throws Exception { Method createBondMethod = btClass.getMethod("cancelBondProcess"); Boolean returnValue = (Boolean) createBondMethod.invoke(device); return returnValue.booleanValue(); } /** * * @param clsShow */ static public void printAllInform(Class clsShow) { try { // 取得所有方法 Method[] hideMethod = clsShow.getMethods(); int i = 0; for (; i < hideMethod.length; i++) { Log.e("method name", hideMethod[i].getName() + ";and the i is:" + i); } // 取得所有常量 Field[] allFields = clsShow.getFields(); for (i = 0; i < allFields.length; i++) { Log.e("Field name", allFields[i].getName()); } } catch (SecurityException e) { // throw new RuntimeException(e.getMessage()); e.printStackTrace(); } catch (IllegalArgumentException e) { // throw new RuntimeException(e.getMessage()); e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }</b> 执行时直接使用: <b>public static boolean pair(String strAddr, String strPsw) { boolean result = false; BluetoothAdapter bluetoothAdapter = BluetoothAdapter .getDefaultAdapter(); bluetoothAdapter.cancelDiscovery(); if (!bluetoothAdapter.isEnabled()) { bluetoothAdapter.enable(); } if (!BluetoothAdapter.checkBluetoothAddress(strAddr)) { // 检查蓝牙地址是否有效 Log.d("mylog", "devAdd un effient!"); } BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { try { Log.d("mylog", "NOT BOND_BONDED"); ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对 ClsUtils.createBond(device.getClass(), device); remoteDevice = device; // 配对完毕就把这个设备对象传给全局的remoteDevice result = true; } catch (Exception e) { // TODO Auto-generated catch block Log.d("mylog", "setPiN failed!"); e.printStackTrace(); } // } else { Log.d("mylog", "HAS BOND_BONDED"); try { ClsUtils.createBond(device.getClass(), device); ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对 ClsUtils.createBond(device.getClass(), device); remoteDevice = device; // 如果绑定成功,就直接把这个设备对象传给全局的remoteDevice result = true; } catch (Exception e) { // TODO Auto-generated catch block Log.d("mylog", "setPiN failed!"); e.printStackTrace(); } } return result; }

⑵ 如何使用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回调。你必须扩展这个类并实现回调方法接收更新应用程序的注册状态和蓝牙通道状态的变化。

⑶ android蓝牙通信开发有几种方案

  1. android 4.0以下使用 spp协议, 简单

  2. 4.0以上可以使用 BLE协议, 比较复杂

⑷ android 蓝牙 开发问题

public boolean setName(String name)
Set the friendly Bluetooth name of the local Bluetoth adapter.
This name is visible to remote Bluetooth devices.
Valid Bluetooth names are a maximum of 248 UTF-8 characters, however many
remote devices can only display the first 40 characters, and some may be limited
to just 20.

文档中不是有说明吗!
最大有效值是用utf-8编码的248个字符,然而有些蓝牙设备最多能显示40个字符,....20char。

⑸ android 4.0 蓝牙开发 怎么入手

本文介绍Android ble 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用,如果手机系统版本API level < 18,也是用不了蓝牙4.0的哦。

首先发一下官方的demo,有兴趣的可以过去看看:http://developer.android.com/guide/topics/connectivity/bluetooth-le.html。android系统4.3以上,手机支持蓝牙4.0,具有搜索,配对,连接,发现服务及特征值,断开连接等功能,下载地址:http://download.csdn.net/detail/lqw770737185/8116019。

一、了解api及概念

1.1 BluetoothGatt

继承BluetoothProfile,通过BluetoothGatt可以连接设备(connect),发现服务(discoverServices),并把相应地属性返回到BluetoothGattCallback

1.2 BluetoothGattCharacteristic

相当于一个数据类型,它包括一个value和0~n个value的描述(BluetoothGattDescriptor)

1.3 BluetoothGattDescriptor

描述符,对Characteristic的描述,包括范围、计量单位等

1.4 BluetoothGattService

服务,Characteristic的集合。

1.5 BluetoothProfile

一个通用的规范,按照这个规范来收发数据。

1.6 BluetoothManager

通过BluetoothManager来获取BluetoothAdapter

BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
1.7 BluetoothAdapter

一个Android系统只有一个BluetoothAdapter ,通过BluetoothManager 获取

BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
1.8 BluetoothGattCallback

已经连接上设备,对设备的某些操作后返回的结果。这里必须提醒下,已经连接上设备后的才可以返回,没有返回的认真看看有没有连接上设备。

private BluetoothGattCallback GattCallback = new BluetoothGattCallback() {
// 这里有9个要实现的方法,看情况要实现那些,用到那些就实现那些
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState){};
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status){};
};
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
BluetoothGatt gatt = device.connectGatt(this, false, mGattCallback);
1.8.1:notification对应onCharacteristicChanged;

gatt.setCharacteristicNotification(characteristic, true);
1.8.2:readCharacteristic对应onCharacteristicRead;

gatt.readCharacteristic(characteristic);
1.8.3: writeCharacteristic对应onCharacteristicWrite;

gatt.wirteCharacteristic(mCurrentcharacteristic);
1.8.4:连接蓝牙或者断开蓝牙 对应 onConnectionStateChange;

1.8.5: readDescriptor对应onDescriptorRead;

1.8.6:writeDescriptor对应onDescriptorWrite;

gatt.writeDescriptor(descriptor);
1.8.7:readRemoteRssi对应onReadRemoteRssi;

gatt.readRemoteRssi()
1.8.8:executeReliableWrite对应onReliableWriteCompleted;

1.8.9:discoverServices对应onServicesDiscovered。

gatt.discoverServices()
1.9 BluetoothDevice

扫描后发现可连接的设备,获取已经连接的设备

二、开启蓝牙权限

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
如果 android.hardware.bluetooth_le设置为false,可以安装在不支持的设备上使用,判断是否支持蓝牙4.0用以下代码就可以了

if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "设备不支持蓝牙4.0", Toast.LENGTH_SHORT).show();
finish();
}
三、对蓝牙的启动关闭操作

1、利用系统默认开启蓝牙对话框

if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
2、后台打开蓝牙,不做任何提示,这个也可以用来自定义打开蓝牙对话框啦

mBluetoothAdapter.enable();
3、后台关闭蓝牙

mBluetoothAdapter.disable();
四、扫描设备,连接设备,获取设备信息 ,断开连接设备,自行查看官方demo,还是看demo比较清晰啊

⑹ 有关蓝牙的Android开发问题

public boolean setName(String name)
Set the friendly Bluetooth name of the local Bluetoth adapter.
This name is visible to remote Bluetooth devices.
Valid Bluetooth names are a maximum of 248 UTF-8 characters, however many
remote devices can only display the first 40 characters, and some may be limited
to just 20.

文档中不是有说明吗!
最大有效值是用utf-8编码的248个字符,然而有些蓝牙设备最多能显示40个字符,....20char。

⑺ Android蓝牙开发代码怎么写

开启蓝牙设备和设置可见时间:

privatevoidsearch(){
BluetoothAdapteradapter=BluetoothAdapter.getDefaultAdapter();
if(!adapter.isEnabled()){
adapter.enable();
}
Intentenable=newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,3600);//3600为蓝牙设备可见时间
startActivity(enable);
IntentsearchIntent=newIntent(this,ComminuteActivity.class);
startActivity(searchIntent);
}

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

http://www.cnblogs.com/wenjiang/p/3200138.html

⑻ 如何实现android蓝牙开发 自动配对连接,并不弹出提示框

在源码 BluetoothDevice 类中还有两个隐藏方法 cancelBondProcess()和cancelPairingUserInput() 这两个方法一个是取消配对进程一个是取消用户输入 下面是自动配对的代码 Mainfest,xml注册 1 <</code>receiver android:name="." > 2 <</code>intent-filter> 3 <</code>action android:name="android.bluetooth.device.action.PAIRING_REQUEST" /> 4 </</code>intent-filter> 5 </</code>receiver> 自己在收到广播时处理并将预先输入的密码设置进去 01 public class extends BroadcastReceiver 02 { 03 04 String strPsw = "0"; 05 06 @Override 07 public void onReceive(Context context, Intent intent) 08 { 09 // TODO Auto-generated method stub 10 if (intent.getAction().equals( 11 "android.bluetooth.device.action.PAIRING_REQUEST")) 12 { 13 BluetoothDevice btDevice = intent 14 .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 15 16 // byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234"); 17 // device.setPin(pinBytes); 18 Log.i("tag11111", "ddd"); 19 try 20 { 21 ClsUtils.setPin(btDevice.getClass(), btDevice, strPsw); // 手机和蓝牙采集器配对 22 ClsUtils.createBond(btDevice.getClass(), btDevice); 23 ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice); 24 } 25 catch (Exception e) 26 { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 } 31 32 33 } 34 } 001 002 import java.lang.reflect.Field; 003 import java.lang.reflect.Method; 004 005 import android.bluetooth.BluetoothDevice; 006 import android.util.Log; 007 public class ClsUtils 008 { 009 010 014 static public boolean createBond(Class btClass, BluetoothDevice btDevice) 015 throws Exception 016 { 017 Method createBondMethod = btClass.getMethod("createBond"); 018 Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice); 019 return returnValue.booleanValue(); 020 } 021 022 026 static public boolean removeBond(Class btClass, BluetoothDevice btDevice) 027 throws Exception 028 { 029 Method removeBondMethod = btClass.getMethod("removeBond"); 030 Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice); 031 return returnValue.booleanValue(); 032 } 033 034 static public boolean setPin(Class btClass, BluetoothDevice btDevice, 035 String str) throws Exception 036 { 037 try 038 { 039 Method removeBondMethod = btClass.getDeclaredMethod("setPin", 040 new Class[] 041 {byte[].class}); 042 Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice, 043 new Object[] 044 {str.getBytes()}); 045 Log.e("returnValue", "" + returnValue); 046 } 047 catch (SecurityException e) 048 { 049 // throw new RuntimeException(e.getMessage()); 050 e.printStackTrace(); 051 } 052 catch (IllegalArgumentException e) 053 { 054 // throw new RuntimeException(e.getMessage()); 055 e.printStackTrace(); 056 } 057 catch (Exception e) 058 { 059 // TODO Auto-generated catch block 060 e.printStackTrace(); 061 } 062 return true; 063 064 } 065 066 // 取消用户输入 067 static public boolean cancelPairingUserInput(Class btClass, 068 BluetoothDevice device) 069 070 throws Exception 071 { 072 Method createBondMethod = btClass.getMethod("cancelPairingUserInput"); 073 // cancelBondProcess() 074 Boolean returnValue = (Boolean) createBondMethod.invoke(device); 075 return returnValue.booleanValue(); 076 } 077 078 // 取消配对 079 static public boolean cancelBondProcess(Class btClass, 080 BluetoothDevice device) 081 082 throws Exception 083 { 084 Method createBondMethod = btClass.getMethod("cancelBondProcess"); 085 Boolean returnValue = (Boolean) createBondMethod.invoke(device); 086 return returnValue.booleanValue(); 087 } 088 089 093 static public void printAllInform(Class clsShow) 094 { 095 try 096 { 097 // 取得所有方法 098 Method[] hideMethod = clsShow.getMethods(); 099 int i = 0; 100 for (; i < hideMethod.length; i++) 101 { 102 Log.e("method name", hideMethod[i].getName() + ";and the i is:" 103 + i); 104 } 105 // 取得所有常量 106 Field[] allFields = clsShow.getFields(); 107 for (i = 0; i < allFields.length; i++) 108 { 109 Log.e("Field name", allFields[i].getName()); 110 } 111 } 112 catch (SecurityException e) 113 { 114 // throw new RuntimeException(e.getMessage()); 115 e.printStackTrace(); 116 } 117 catch (IllegalArgumentException e) 118 { 119 // throw new RuntimeException(e.getMessage()); 120 e.printStackTrace(); 121 } 122 catch (Exception e) 123 { 124 // TODO Auto-generated catch block 125 e.printStackTrace(); 126 } 127 } 128 } 执行时直接使用: 01 public static boolean pair(String strAddr, String strPsw) 02 { 03 boolean result = false; 04 BluetoothAdapter bluetoothAdapter = BluetoothAdapter 05 .getDefaultAdapter(); 06 07 bluetoothAdapter.cancelDiscovery(); 08 09 if (!bluetoothAdapter.isEnabled()) 10 { 11 bluetoothAdapter.enable(); 12 } 13 14 if (!BluetoothAdapter.checkBluetoothAddress(strAddr)) 15 { // 检查蓝牙地址是否有效 16 17 Log.d("mylog", "devAdd un effient!"); 18 } 19 20 BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr); 21 22 if (device.getBondState() != BluetoothDevice.BOND_BONDED) 23 { 24 try 25 { 26 Log.d("mylog", "NOT BOND_BONDED"); 27 ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对 28 ClsUtils.createBond(device.getClass(), device); 29 remoteDevice = device; // 配对完毕就把这个设备对象传给全局的remoteDevice 30 result = true; 31 } 32 catch (Exception e) 33 { 34 // TODO Auto-generated catch block 35 36 Log.d("mylog", "setPiN failed!"); 37 e.printStackTrace(); 38 } // 39 40 } 41 else 42 { 43 Log.d("mylog", "HAS BOND_BONDED"); 44 try 45 { 46 ClsUtils.createBond(device.getClass(), device); 47 ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对 48 ClsUtils.createBond(device.getClass(), device); 49 remoteDevice = device; // 如果绑定成功,就直接把这个设备对象传给全局的remoteDevice 50 result = true; 51 } 52 catch (Exception e) 53 { 54 // TODO Auto-generated catch block 55 Log.d("mylog", "setPiN failed!"); 56 e.printStackTrace(); 57 } 58 } 59 return result; 60 }

⑼ 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);
}
}

⑽ delphi android蓝牙4.0开发

就是串口通讯 安卓系统

枚举dev目录下的文件 就是安卓的设备列表
你可以找找看 其中就有蓝牙设备
蓝牙本身是串口通讯 在安卓下 是用读写文件方式就可以收发串口数据。
那就需要获取读写权限 但问题是在获取权限后 delphi Xe虽然可以打开文件 但我不知道如何设置波特率。 也没找到资料。
所以我最后的解决办法是 用C写了一个安卓下收发串口的so库文件 然后delphi去调用这个so文件。这样实现了delphi对串口的控制。

热点内容
ipad文件加密 发布:2024-05-02 08:20:30 浏览:442
粉土压缩模量 发布:2024-05-02 07:53:59 浏览:805
国都证券初始密码是多少 发布:2024-05-02 07:46:39 浏览:109
shell脚本和linux命令行 发布:2024-05-02 07:37:54 浏览:968
自己的服务器搭建微信小程序商城 发布:2024-05-02 07:36:26 浏览:426
php单行注释 发布:2024-05-02 07:36:22 浏览:958
买车哪些配置必备 发布:2024-05-02 07:30:20 浏览:52
华为手机的自带铃声文件夹 发布:2024-05-02 07:20:14 浏览:501
xp系统开机密码怎么设置 发布:2024-05-02 06:49:48 浏览:759
柱加密区公式 发布:2024-05-02 06:40:19 浏览:4