編輯:關於Android編程
Android 4.3(API Level 18)開始引入Bluetooth Low Energy(BLE,低功耗藍牙)的核心功能並提供了相應的API,應用程序通過這些api可以掃描設備、查詢services,讀寫設備的characteristics(屬性特征)。對比傳統的藍牙,BLE的設計能夠顯著減低功耗。這讓Android應用程序與BLE設備之間的低功耗通訊成為可能,例如距離傳感器、心率監視器、健身設備等等。
* Generic Attribute Profile(GATT):GATT profile是一種關於發送和接收簡短數據片段的一般規范,這種簡短數據片段例如在BLE的連接上眾所周知的“attribute(屬性)”等。當前所有低功耗應用程序的profile都基於GATT。另外,藍牙技術聯盟(Bluetooth SIG)已經為很多BLE設備定義了profile。profile就是一種在指定的應用程序中定義設備如何工作的規范。注意,一台設備可以實現多個profile。例如,一台設備可以包含心率監視器和電池電量探測器。
* Attribute Protocol(ATT,屬性協議):GATT構建在ATT的基礎之上,因此也總被成為GATT/ATT。ATT針對BLE設備的運行進行了優化。為此,它會盡可能的使用更少的字節數據。每一個屬性都通過UUID來唯一確定。UUID就是一個標准128位格式的字符串ID,用於唯一確定一個信息。屬性通過ATT協議格式化為characteristics和services後進行傳輸。
* Characteristic:一個characteristic中包含一個值,以及0個或多個用於描述characteristic值的descriptor。可以將characteristic認為是一種類型,類似於一個類。
* Descriptor:Descriptor(描述符)中定義的屬性用於描述一個characteristic值。例如,一個descriptor可以為一個characteristic的值指定一個在可接受范圍內的可讀性描述,或者為一個characteristic的值指定一個計量單位。
* Service:一個service是一個characteristic的集合。例如,你可以持有一個名為“心率監視器”的service,它包含的characteristic例如“心率測量”。你可以在bluetooth.org上找到一系列基於GATT的profile和service。
以下是一台Android設備與BLE設備交互時的一些適用角色和職能:
* 中央設備和外圍設備。這適用於BLE自身的連接。擔任中央設備角色的設備負責掃描和搜索廣告,擔任外圍設備的角色負責發送廣告。
* GATT服務端和GATT客戶端。這取決於兩台設備在建立連接後如何互相通信。
為了理解這之間的區別,想象你有一台Android手機和一台BLE設備作為活動追蹤器。手機將擔任中央設備角色;活動追蹤器將擔任外圍設備角色(你需要具備兩種角色才能建立一個BLE連接,兩者都擔任外圍設備角色不能互相通信,同樣兩者都擔任中央設備角色也不能互相通信)。
一旦手機和活動追蹤器建立連接,它們就可以互相傳輸GATT媒體數據。根據它們傳輸的數據,其中一方需要擔任服務端的角色。例如,如果活動追蹤器想要發送傳感器數據給手機,活動追蹤器就需要擔任服務端的角色。如果活動追蹤器想要接收手機的數據,手機就需要擔任服務端的角色。
在本片文檔的例子中,Android應用程序(運行在Android設備上)是GATT客戶端。應用程序從GATT服務端獲取數據,這個服務端由支持Heart Rate Profile的BLE心率監視器設備擔任。但是你可以交替讓你的Android應用程序扮演GATT服務端的角色。具體參考BluetoothGattService。
為了在你的應用程序中使用Bluetooth的功能,你必須聲明android.permission.BLUETOOTH權限。你需要這個權限來執行一些藍牙通信的操作,例如請求鏈接,接受連接,還有傳輸數據。
如果你想讓你的應用程序進行設備掃描或者管理藍牙設置,你必須同時聲明android.permission.BLUETOOTH_ADMIN權限。注意,如果你使用BLUETOOTH_ADMIN權限,你必須同時聲明BLUETOOTH權限。
在你的應用程序manifest文件中聲明藍牙權限,例如:
如果你想聲明你的應用程序只能在支持BLE的設備上運行,可以將下面聲明包含進你的應用程序manifest文件中:
然而,如果你想讓你的應用程序也能夠在不支持BLE的設備上運行,你就應該將上面標簽中的屬性設置為required="false"。然後在運行的過程中使用PackageManager.hasSystemFeature()方法來判斷設備是否支持BLE:
// 使用下面的方法來確定設備是否支持BLE, 然後你可以選擇禁用BLE的功能
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}在你的應用程序通過BLE進行通信之前,你需要確認設備是否支持BLE。如果支持,還要再確認是否已經啟用。注意這個檢查步驟只有在
如果不支持BLE,你應該優雅的禁止一些使用BLE的功能。如果支持BLE,但是目前禁用了,那麼你需要在不離開你的應用程序狀態下,請求用戶啟用藍牙用能。這個過程需要使用BluetoothAdapter,分兩個步驟完成:
基本上所有使用藍牙的activity都需要BluetoothAdapter。BluetoothAdapter代表了設備本身的藍牙適配器(藍牙發送接收器)。在整個系統中有一個BluetoothAdapter對象,你的應用程序可以使用這個對象進行交互。下面的代碼片段展示了如果獲取這個適配器。注意下面的這種方法使用getSystemService()方法來獲取一個BluetoothManager實例,之後再通過BluetoothManager獲取BluetoothAdapter。Android 4.3(API Level 18)才開始支持BluetoothManager:
// 初始化藍牙適配器.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();下一步,你需要確保藍牙已經啟動。調用isEnable()方法來檢查藍牙當前是否已經啟用。如果方法返回false,說明藍牙被禁用了。下面的代碼片段中檢查藍牙是否已經啟用。如果沒有啟用,代碼片段會顯示一個錯誤提示用戶去設置中啟用藍牙:
private BluetoothAdapter mBluetoothAdapter;
...
// 確認設備支持藍牙並且已經啟用. 如果沒有,
// 顯示一個對話框要求用戶授權啟用藍牙.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}搜索BLE設備,你可以使用startLeScan()方法。這個方法需要一個BluetoothAdapter.LeScanCallback對象作為參數。你必須實現這個callback接口,因為掃描的結果會通過這個接口返回。由於搜索設備是比較耗電的操作,你應該遵循以下指南使用:
* 一旦你找到目標設備,應該馬上停止搜索。
* 不要死循環搜索,並設置搜索的最長時間。一台以前可以訪問的設備可能已經移出了可檢測范圍,繼續掃描只會消耗電量。
下面的代碼片段展示了如何開始和停止搜索:
/**
* 掃描和顯示可訪問BLE設備的Activity.
*/
public class DeviceScanActivity extends ListActivity {
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
// 10秒鐘後停止掃描.
private static final long SCAN_PERIOD = 10000;
...
private void scanLeDevice(final boolean enable) {
if (enable) {
// 在預定義的掃描時間周期後停止掃描.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
...
}
...
}如果你只想搜索指定類型的外圍設備,你可以替換成startLeScan(UUID[], BluetoothAdapter.LeScanCallback)方法,並提供一個你的應用程序所支持的GATT服務的UUID對象數組。
下面是一個BluetoothAdapter.LeScanCallback的實現,它是一個用於接收BLE搜索結果的接口:
private LeDeviceListAdapter mLeDeviceListAdapter;
...
// 設備搜索回調接口.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};注意:正如Bluetooth文檔中所描述的,在同一個時間你只能搜索BLE設備或者搜索傳統藍牙設備。你不能同時搜索BLE設備和傳統藍牙設備。
與BLE設備交互的第一步就是要連接上它——更准確的說,是連接設備上的GATT服務。連接BLE設備上的GATT服務,你可以使用connectGatt()方法。這個方法需要三個參數:一個Context對象,autoConnect(一個表示是否當BLE設備可訪問時馬上自動連接的boolean值),還有一個BluetoothGattCallbackduixiang:
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
上面的代碼會連接BLE設備管理的GATT服務,並返回一個BluetoothGatt實例,通過這個實例就可以執行GATT客戶端的相關操作。這個調用者(Android應用程序)就是GATT客戶端。裡面的BluetoothGattCallback對象用於交付操作結果給客戶端,例如連接狀態,還有將來一些GATT客戶端操作的結果。
在這個例子中,BLE應用程序提供了一個activity(DeviceControlActivity)來連接、顯示數據,和顯示BLE設備所支持的GATT的service以及characteristic。基於用戶的輸入,這個activity會和一個名為BluetoothLeService的Service通信,這個service通過Android BLE的API與BLE設備進行交互。
// 一個通過Android BLE API與BLE設備進行交互的service.
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private int mConnectionState = STATE_DISCONNECTED;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
public final static UUID UUID_HEART_RATE_MEASUREMENT =
UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
// BLE API定義的各個回調方法.
private final BluetoothGattCallback mGattCallback =
new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "連接GATT服務.");
Log.i(TAG, "嘗試開始service搜索:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "斷開GATT server連接.");
broadcastUpdate(intentAction);
}
}
@Override
// New services discovered
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
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
...
};
...
}當一個特定的的回調方法被調用的時候,它就會適當調用broadcastUpdate()幫助方法並傳遞一個操作標識。注意本節中的數據是根據藍牙心率測量的profile規范解析的:
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
// 按照心率測量的profile進行的特定處理.
// 按照麼一個profile規范進行數據解析.
if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
int flag = characteristic.getProperties();
int format = -1;
if ((flag & 0x01) != 0) {
format = BluetoothGattCharacteristic.FORMAT_UINT16;
Log.d(TAG, "Heart rate format UINT16.");
} else {
format = BluetoothGattCharacteristic.FORMAT_UINT8;
Log.d(TAG, "Heart rate format UINT8.");
}
final int heartRate = characteristic.getIntValue(format, 1);
Log.d(TAG, String.format("Received heart rate: %d", heartRate));
intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
} else {
// 針對其他profiles, 將數據格式化為16禁止數據.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for(byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
intent.putExtra(EXTRA_DATA, new String(data) + "\n" +
stringBuilder.toString());
}
}
sendBroadcast(intent);
}
回到DeviceControlActivity,下面的事件通過一個BroadcaseReceiver處理:
// 處理Service發送過來的各種時間.
// ACTION_GATT_CONNECTED: 連接上了一個GATT服務.
// ACTION_GATT_DISCONNECTED: 斷開了一個GATT服務.
// ACTION_GATT_SERVICES_DISCOVERED: 發現了GATT服務.
// ACTION_DATA_AVAILABLE: 從設備接收到數據. 這裡可能是一個讀取或者通知操作的結果。
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.
ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
// 顯示所有支持的service和characteristic。
displayGattServices(mBluetoothLeService.getSupportedGattServices());
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};一旦你的Android應用程序連接上了一個GATT服務並且發現了設備上的service,就可以在支持讀寫的地方讀寫屬性。例如,下面的代碼片段通過迭代服務的service和characteristic,並將它們顯示在界面上:
public class DeviceControlActivity extends Activity {
...
// 演示如何迭代所支持的GATT Services/Characteristics.
// 在這個例子中,我們填充綁定到ExpandableListView的數據結構。
private void displayGattServices(List gattServices) {
if (gattServices == null) return;
String uuid = null;
String unknownServiceString = getResources().
getString(R.string.unknown_service);
String unknownCharaString = getResources().
getString(R.string.unknown_characteristic);
ArrayList> gattServiceData =
new ArrayList>();
ArrayList>> gattCharacteristicData
= new ArrayList>>();
mGattCharacteristics =
new ArrayList>();
// 循環迭代可訪問的GATT Services.
for (BluetoothGattService gattService : gattServices) {
HashMap currentServiceData =
new HashMap();
uuid = gattService.getUuid().toString();
currentServiceData.put(
LIST_NAME, SampleGattAttributes.
lookup(uuid, unknownServiceString));
currentServiceData.put(LIST_UUID, uuid);
gattServiceData.add(currentServiceData);
ArrayList> gattCharacteristicGroupData =
new ArrayList>();
List gattCharacteristics =
gattService.getCharacteristics();
ArrayList charas =
new ArrayList();
// 循環迭代可訪問的Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic :
gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap currentCharaData =
new HashMap();
uuid = gattCharacteristic.getUuid().toString();
currentCharaData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid,
unknownCharaString));
currentCharaData.put(LIST_UUID, uuid);
gattCharacteristicGroupData.add(currentCharaData);
}
mGattCharacteristics.add(charas);
gattCharacteristicData.add(gattCharacteristicGroupData);
}
...
}
...
}
BLE應用程序要求在設備的某個指定characteristic改變的時候接收到通知是很常見。下面的代碼片段展示了如何通過使用setCharacteristicNotification()為一個characteristic設置通知:
private BluetoothGatt mBluetoothGatt;
BluetoothGattCharacteristic characteristic;
boolean enabled;
...
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
...
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);一旦為一個characteristic啟用了通知,當遠程設備上的characteristic改變的時候就會觸發onCharacteristicChanged()方法:
@Override
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}一旦你的應用程序使用完BLE設備,你應該調用close()方法,這樣系統才能適當釋放占用的資源:
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}原文地址:http://developer.android.com/guide/topics/connectivity/bluetooth-le.html
Android使用adb命令往模擬器裡安裝軟件
我將模擬器解壓到C:\android-sdk-windows\在C:\android-sdk-windows\platform-tools這個文件夾裡有個a
android圖片處理之圖像模糊
這篇文章將給大家介紹android圖片處理的高效做法,大家有需求的時候可以參考一下。首先我要說明一下本實例中實現的效果(我還不會制作gif圖,如果誰會的話,希望可以教一下
Android開發最佳實踐
本文是Futurice公司的Android開發人員總結的最佳實踐,遵循這些准則可以避免重復制造輪子。如果你對iOS或者WindowsPhone開發感興趣,那麼也請看看iO
Android自定義控件:老版優酷的三級菜單(效果圖 + Demo)
效果圖: 整體思路就是這樣,接下來就是一些操作了: 代碼: 1、MyAnimation類: public class MyAnimation{ public s