當前位置:首頁 » 安卓系統 » 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對串口的控制。

熱點內容
如何配置全局地址池視頻 發布:2022-10-05 03:08:33 瀏覽:826
為什麼安卓機沒有來電閃光 發布:2022-10-05 03:02:01 瀏覽:23
補丁解壓到哪裡 發布:2022-10-05 02:52:11 瀏覽:959
新裝寬頻密碼多少合適 發布:2022-10-05 02:52:05 瀏覽:296
oraclesql文件夾 發布:2022-10-05 02:49:23 瀏覽:339
加密博客 發布:2022-10-05 02:49:15 瀏覽:610
單幅存儲 發布:2022-10-05 02:48:05 瀏覽:266
沒有id密碼怎麼注銷 發布:2022-10-05 02:47:25 瀏覽:163
monkeyrunner腳本錄制 發布:2022-10-05 02:46:00 瀏覽:761
python中與的用法 發布:2022-10-05 02:41:03 瀏覽:110