導航:首頁 > 操作系統 > 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藍牙開發相關的資料

熱點內容
老程序員編程步驟 瀏覽:303
物理去除加密軟體 瀏覽:225
匯編語言可調試編譯器 瀏覽:447
jpeg如何轉成pdf 瀏覽:841
微機室為什麼有伺服器 瀏覽:657
安卓手機怎麼打語音電話不斷網 瀏覽:458
單片機匯編頭文件 瀏覽:946
juniper命令行 瀏覽:68
程序員咨詢銷售工作怎麼樣 瀏覽:782
蘋果文件伺服器是什麼 瀏覽:180
企業透明加密軟體有監視功能嗎 瀏覽:494
桌面的運行命令 瀏覽:9
主流廠商伺服器維護流程是什麼 瀏覽:807
壓縮棉的被子先洗洗在用 瀏覽:242
批處理bat代碼和文件夾 瀏覽:298
怎麼交叉編譯tslib14 瀏覽:494
致程序員生產力飆升 瀏覽:762
程序員害怕下班嗎 瀏覽:108
鐵路漢宜線加密網實景效果圖 瀏覽:929
php工作難找 瀏覽:442