2023年7月7日发(作者:)
程序结合了网上的开源程序。
othlegatt包中的代码有修改,res文件夹和中的代码没有修改.
下面直接上代码,并把修改的地方用红色指出来。
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* /licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package othlegatt;
import ty;
import tivity;
import othAdapter;
import othDevice;
import othManager;
import t;
import ;
import eManager;
import ;
import r;
import Inflater;
import ;
import em;
import ;
import oup;
import apter;
import ew;
import ew;
import ;
import ist;
/**
* Activity for scanning and displaying available Bluetooth LE devices.
*/
public class DeviceScanActivity extends ListActivity {
private LeDeviceListAdapter mLeDeviceListAdapter;//适配器adapter,存放搜寻到的设备信息
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private static final int REQUEST_ENABLE_BT = 1;
// 10秒后停止查找搜索.
private static final long SCAN_PERIOD = 10000;
@Override
public void onCreate(Bundle savedInstanceState) {
te(savedInstanceState);
getActionBar().setTitle(_devices);//BLE Device Scan
mHandler = new Handler();
// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
if
(!getPackageManager().hasSystemFeature(E_BLUETOOTH_LE)) {
xt(this, _not_supported,
_SHORT).show();
finish();
}
// 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器
//(API必须在以上android4.3或以上和版本)
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(OTH_SERVICE);
mBluetoothAdapter = pter();
// 检查设备上是否支持蓝牙
if (mBluetoothAdapter == null) {
xt(this, _bluetooth_not_supported,
_SHORT).show();
finish();
return;
}
}
//选项菜单(optionsMenu)。在Menu对象的方法来添加菜单或者是子菜单。 @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(, menu);
//mScanning代表搜寻与否,初始值为FALSE
if (!mScanning)
{
em(_stop).setVisible(false);
em(_scan).setVisible(true);//正在搜索
em(_refresh).setActionView(null);
} else {
em(_stop).setVisible(true);//停止搜索
em(_scan).setVisible(false);
em(_refresh).setActionView(
bar_indeterminate_progress);
}
return true;
}
//响应菜单项单击事件,切换搜索与否
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (mId()) {
case _scan:
();//清空适配器,重新搜索
scanLeDevice(true);
break;
case _stop:
scanLeDevice(false);
break;
}
return true;
}
//恢复,Activity时候被回调。
@Override
protected void onResume() {
me();
// 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!led()) {
if (!led()) {
Intent enableBtIntent = new
Intent(_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();//新建适配器
setListAdapter(mLeDeviceListAdapter);//数据绑定
scanLeDevice(true);
}
//子activity完成后,需要带回数据给主activity,需要回调该方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
//当运算符两边的表达式的结果都为true时,整个运算结果才为true
if (requestCode == REQUEST_ENABLE_BT && resultCode ==
_CANCELED) {
finish();
return;
}
vityResult(requestCode, resultCode, data);
}
//暂停activity时候被回调
@Override
protected void onPause() {
e();
scanLeDevice(false);
();
}
//ListView中的条目短按和长按事件,他们的处理方式是不同的。对于短按事件,处理起来比较简单,
//我们只需要覆盖ListActivity的onListItemClick()方法
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = ice(position);
if (device == null) return;
final Intent intent = new Intent(this, );
ra(_DEVICE_NAME, e());
ra(_DEVICE_ADDRESS,
ress());
//putExtra("A",B)中,AB为键值对,第一个参数为键名,第二个参数为键对应的值。
//顺便提一下,如果想取出Intent对象中的这些值,需要在你的另一个Activity中用getXXXXXExtra方法,
//注意需要使用对应类型的方法,参数为键名
if (mScanning) {
Scan(mLeScanCallback); mScanning = false;
}
startActivity(intent);//启动activity
}
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
//
layed(new Runnable() {
@Override
public void run() {
mScanning = false;
Scan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
eScan(mLeScanCallback);
} else {
mScanning = false;
Scan(mLeScanCallback);
}
invalidateOptionsMenu();
//在运行时更改选项菜单
//随时动态改变OptionMenu就要实现onPrepareOptionsMenu()方法
}
//继承BaseAdapter,实现adapter,存放listview中的数据。
//实现自己的adapter
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList
private LayoutInflater mInflator;
public LeDeviceListAdapter() //构造函数
{
super();
mLeDevices = new ArrayList
mInflator = outInflater();
}
//对象中的方法,addDevice
public void addDevice(BluetoothDevice device)
{ if(!ns(device)) {
(device);
}
}
public BluetoothDevice getDevice(int position) {
return (position);
}
public void clear() {
();
}
@Override
public int getCount() {
return ();
}
@Override
public Object getItem(int i) {
return (i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = e(em_device, null);
viewHolder = new ViewHolder();
Address = (TextView)
ewById(_address);
Name = (TextView)
ewById(_name);
(viewHolder);
//View中的setTag(Onbect)表示给View添加一个格外的数据,以后可以用getTag()将这个数据取出来。
} else {
viewHolder = (ViewHolder) (); }
BluetoothDevice device = (i);
final String deviceName = e();
if (deviceName != null && () > 0)
t(deviceName);
else
t(n_device);
t(ress());
return view;
}
}
// Device scan callback.
private Callback mLeScanCallback =
new Callback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
ice(device);
DataSetChanged();
}
});
}
};
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
}
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* /licenses/LICENSE-2.0
* * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package othlegatt;
import p;
/**
* This class includes a small subset of standard GATT attributes for demonstration purposes.
*/
public class SampleGattAttributes {
private static HashMap
public static String HEART_RATE_MEASUREMENT =
"6e400001-b5a3-f393-e0a9-e50e24dcca9e";
public static String CLIENT_CHARACTERISTIC_CONFIG =
"00002902-0000-1000-8000-00805f9b34fb";
static {
// Sample Services.
("0000180d-0000-1000-8000-00805f9b34fb", "Heart Rate Service");
("0000180a-0000-1000-8000-00805f9b34fb", "Device Information
Service");
// Sample Characteristics.
(HEART_RATE_MEASUREMENT, "Heart Rate Measurement");
("00002a29-0000-1000-8000-00805f9b34fb", "Manufacturer Name
String");
}
public static String lookup(String uuid, String defaultName) {
String name = (uuid);
return name == null ? defaultName : name;
}
}
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* * /licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package othlegatt;
import ty;
import othGattCharacteristic;
import othGattService;
import astReceiver;
import entName;
import t;
import ;
import Filter;
import eConnection;
import ;
import r;
import ;
import ;
import em;
import ;
import xt;
import ableListView;
import ExpandableListAdapter;
import ew;
import ist;
import p;
import ;
/**
* For a given BLE device, this Activity provides the user interface to connect, display data,
* and display GATT services and characteristics supported by the device. The Activity
* communicates with {@code BluetoothLeService}, which in turn interacts with the
* Bluetooth LE API.
*/
public class DeviceControlActivity extends Activity {
private final static String TAG = pleName();
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
private TextView mConnectionState;
private TextView mDataField;
private String mDeviceName;
private String mDeviceAddress;
private ExpandableListView mGattServicesList;
private BluetoothLeService mBluetoothLeService;
private ArrayList
new ArrayList
private boolean mConnected = false;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
// Code to manage Service lifecycle.
//这个对象,是绑定service的第二个参数
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service)
{
mBluetoothLeService = ((inder) service).getService();
//初始化完成,返回TRUE
if (!lize())
{
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
//因为已经初始化完成,直接调用方法根据地址连接
t(mDeviceAddress);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of
read
// or notification operations.
//广播接收器
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = ion();//这个intent应该是从service来的
if (_GATT_(action)) {
mConnected = true;
updateConnectionState(ted);
invalidateOptionsMenu();
} else if (_GATT_(action))
{
mConnected = false;
updateConnectionState(nected);
invalidateOptionsMenu();
clearUI();
} else if
(_GATT_SERVICES_(action)) {
// Show all the supported services and characteristics on the user interface.
displayGattServices(portedGattServices());
} else if (_DATA_(action)) {
displayData(ingExtra(_DATA));
//putExtra("A",B)中,AB为键值对,第一个参数为键名,第二个参数为键对应的值。
//顺便提一下,如果想取出Intent对象中的这些值,需要在你的另一个Activity中用getXXXXXExtra方法,
//注意需要使用对应类型的方法,参数为键名
}
}
};
// If a given GATT characteristic is selected, check for supported features. This sample
// demonstrates 'Read' and 'Notify' features. See
// /reference/android/bluetooth/ for the complete
// list of supported characteristic features.
private final dClickListener servicesListClickListner =
new dClickListener() {
@Override public boolean onChildClick(ExpandableListView parent, View v, int
groupPosition,
int childPosition, long id) {
if (mGattCharacteristics != null) {
if (groupPosition == 2 && childPosition == 0) {
// 响应第一个子列表项,表示读取蓝牙
// 问题是:长一些的字符串,能马上读取,短字符串,需要发送多次。
final BluetoothGattCharacteristic characteristic = mGattCharacteristics
.get(groupPosition).get(childPosition);
final int charaProp = perties();
if ((charaProp | TY_READ) > 0) {
// If there is an active notification on a
// characteristic, clear
// it first so it doesn't update the data field on the
// user interface.
n("infor");
if (mNotifyCharacteristic != null) {
n("inif");
racteristicNotification(
mNotifyCharacteristic, false);
mNotifyCharacteristic = null;
}
aracteristic(characteristic);
}
if ((charaProp | TY_NOTIFY) > 0)
{
n("inif");
mNotifyCharacteristic = characteristic;
racteristicNotification(
characteristic, true);
}
return true;
}
if (groupPosition == 2 && childPosition == 1) {
// 响应第二个子列表项表示写蓝牙设备
n("setdown");
String str = "a";
byte[] srtbyte = es();
writeCharacteristic(srtbyte);//调用写数据函数
return true;
}
}
return false; }
};
public void writeCharacteristic(byte[] i) {//写数据蓝牙设备
for (ArrayList
for (BluetoothGattCharacteristic LumChar : LumChar0) {
if (LumChar == null) {
n("LumChar null");
return;
}
ue(i);
boolean status = oothGatt
.writeCharacteristic(LumChar);
n("Write Status: " + status);
n("OK");
}
}
}
private void clearUI() {
pter((SimpleExpandableListAdapter) null);
t(_data);
}
@Override
public void onCreate(Bundle savedInstanceState) {
te(savedInstanceState);
setContentView(_services_characteristics);
final Intent intent = getIntent();//得到从另一个activity来的intent
//根据键值得到数据
mDeviceName = ingExtra(EXTRAS_DEVICE_NAME);
mDeviceAddress = ingExtra(EXTRAS_DEVICE_ADDRESS);
// Sets up UI references.
//
((TextView) findViewById(_address)).setText(mDeviceAddress);
mGattServicesList = (ExpandableListView) findViewById(_services_list);
hildClickListener(servicesListClickListner);
mConnectionState = (TextView) findViewById(tion_state);
mDataField = (TextView) findViewById(_value);
getActionBar().setTitle(mDeviceName); getActionBar().setDisplayHomeAsUpEnabled(true);
Intent gattServiceIntent = new Intent(this, );
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onResume() {
me();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = t(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
@Override
protected void onPause() {
e();
unregisterReceiver(mGattUpdateReceiver);
}
@Override
protected void onDestroy() {
roy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
//选项菜单(optionsMenu)。在Menu对象的方法来添加菜单或者是子菜单。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(_services, menu);
if (mConnected) {
em(_connect).setVisible(false);
em(_disconnect).setVisible(true);
} else {
em(_connect).setVisible(true);
em(_disconnect).setVisible(false);
}
return true;
}
//响应菜单项单击事件,切换搜索与否
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(mId()) { case _connect:
t(mDeviceAddress);
return true;
case _disconnect:
nect();
return true;
case :
onBackPressed();
return true;
}
return onsItemSelected(item);
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
t(resourceId);
}
});
}
//设置数据(重点模块)
private void displayData(String data) {
if (data != null) {
t(data);
}
}
// 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
if (gattServices == null) return;
String uuid = null;
String unknownServiceString = getResources().getString(n_service);
String unknownCharaString =
getResources().getString(n_characteristic);
ArrayList
ArrayList
ArrayList
= new ArrayList
mGattCharacteristics = new ArrayList
// Loops through available GATT Services. for (BluetoothGattService gattService : gattServices) {
HashMap
uuid = d().toString();
(
LIST_NAME, (uuid,
unknownServiceString));
(LIST_UUID, uuid);
(currentServiceData);
ArrayList
new ArrayList
List
racteristics();
ArrayList
new ArrayList
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
(gattCharacteristic);
HashMap String>(); uuid = d().toString(); ( LIST_NAME, (uuid, unknownCharaString)); (LIST_UUID, uuid); (currentCharaData); } (charas); (gattCharacteristicGroupData); } SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter( this, gattServiceData, _expandable_list_item_2, new String[] {LIST_NAME, LIST_UUID}, new int[] { 1, 2 }, gattCharacteristicData, _expandable_list_item_2, new String[] {LIST_NAME, LIST_UUID}, new int[] { 1, 2 } ); pter(gattServiceAdapter); } private static IntentFilter makeGattUpdateIntentFilter() { final IntentFilter intentFilter = new IntentFilter(); ion(_GATT_CONNECTED); ion(_GATT_DISCONNECTED); ion(_GATT_SERVICES_DISCOVERED); ion(_DATA_AVAILABLE); return intentFilter; } } /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * /licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package othlegatt; import e; import othAdapter; import othDevice; import othGatt; import othGattCallback; import othGattCharacteristic; import othGattDescriptor; import othGattService; import othManager; import othProfile; import t; import ; import ; import r; import ; import ; import ; /** * Service for managing connection and data communication with a GATT server hosted on a * given Bluetooth LE device. */ public class BluetoothLeService extends Service { private final static String TAG = pleName(); private BluetoothManager mBluetoothManager; private BluetoothAdapter mBluetoothAdapter; private String mBluetoothDeviceAddress; public static 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 = "_GATT_CONNECTED"; public final static String ACTION_GATT_DISCONNECTED = "_GATT_DISCONNECTED"; public final static String ACTION_GATT_SERVICES_DISCOVERED = "_GATT_SERVICES_DISCOVERED"; public final static String ACTION_DATA_AVAILABLE = "_DATA_AVAILABLE"; public final static String EXTRA_DATA = "_DATA"; public final static UUID UUID_HEART_RATE_MEASUREMENT = ring(_RATE_MEASUREMENT); public static UUID CLIENT_CHARACTERISTIC_CONFIG1 ring("6e400003-b5a3-f393-e0a9-e50e24dcca9e"); // Implements callback methods for GATT events that the app cares about. For example, // connection change and services discovered. private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { = @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { n("callback function"); String intentAction; if (newState == _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:" + erServices()); } else if (newState == _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) { n("callback function"); if (status == _SUCCESS) { broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED); } else { Log.w(TAG, "onServicesDiscovered received: " + status); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { n(" read callback function"); if (status == _SUCCESS) { broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); } } @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { n("change callback function"); broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); } }; 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); // n(d()+">>>>>>>>"); // This is special handling for the Heart Rate Measurement profile. Data parsing is // carried out as per profile specifications: // /gatt/characteristics/Pages/?u=_rate_ // if (CLIENT_CHARACTERISTIC_(d())) { // int flag = perties(); // int format = -1; // if ((flag & 0x01) != 0) { // format = _UINT16; // Log.d(TAG, "Heart rate format UINT16."); // } else { // format = _UINT8; // Log.d(TAG, "Heart rate format UINT8."); // } // final int heartRate = Value(format, 1); // Log.d(TAG, ("Received heart rate: %d", heartRate)); // ra(EXTRA_DATA, f(heartRate)); // } else { // // For all other profiles, writes the data formatted in HEX. // // // final byte[] data = ue(); // if (data != null && > 0) { // final StringBuilder stringBuilder = new StringBuilder(); // for(byte byteChar : data) // (("%02X ", byteChar)); // ra(EXTRA_DATA, new String(data) + "n" + ng()); // } // } if (CLIENT_CHARACTERISTIC_(d())) { final byte[] data = ue(); ra(EXTRA_DATA, new String(data)); // String value = ingValue(-1); // n("value:"+value); // ra(EXTRA_DATA,value); } // if (data != null && > 0) { // final StringBuilder stringBuilder = new StringBuilder(); // for(byte byteChar : data) // (("%02X ", byteChar)); // ra(EXTRA_DATA, new String(data) + "n" + ng()); // } sendBroadcast(intent); } public class LocalBinder extends Binder { BluetoothLeService getService() { return ; } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public boolean onUnbind(Intent intent) { // After using a given device, you should make sure that () is called // such that resources are cleaned up properly. In this particular example, close() is // invoked when the UI is disconnected from the Service. close(); return nd(intent); } private final IBinder mBinder = new LocalBinder(); /** * Initializes a reference to the local Bluetooth adapter. * * @return Return true if the initialization is successful. */ public boolean initialize() { // For API level 18 and above, get a reference to BluetoothAdapter through // BluetoothManager. if (mBluetoothManager == null) { mBluetoothManager = (BluetoothManager) getSystemService(OTH_SERVICE); if (mBluetoothManager == null) { Log.e(TAG, "Unable to initialize BluetoothManager."); return false; } } mBluetoothAdapter = pter(); if (mBluetoothAdapter == null) { Log.e(TAG, "Unable to obtain a BluetoothAdapter."); return false; } return true; } /** * 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(othGatt, 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 && (mBluetoothDeviceAddress) && mBluetoothGatt != null) { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (t()) { mConnectionState = STATE_CONNECTING; return true; } else { return false; } } final BluetoothDevice device = oteDevice(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 = tGatt(this, false, mGattCallback); Log.d(TAG, "Trying to create a new connection."); mBluetoothDeviceAddress = address; mConnectionState = STATE_CONNECTING; return true; } /** * Disconnects an existing connection or cancel a pending connection. The disconnection result * is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(othGatt, int, int)} * callback. */ public void disconnect() { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } nect(); } /** * After using a given BLE device, the app must call this method to ensure resources are * released properly. */ public void close() { if (mBluetoothGatt == null) { return; } (); mBluetoothGatt = null; } /** * Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported * asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(othGatt, othGattCharacteristic, int)} * callback. * * @param characteristic The characteristic to read from. */ public void readCharacteristic(BluetoothGattCharacteristic characteristic) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } aracteristic(characteristic); } /** * Enables or disables notification on a give characteristic. * * @param characteristic Characteristic to act on. * @param enabled If true, enable notification. False otherwise. */ public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) { if (mBluetoothAdapter == null || mBluetoothGatt == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } n("setCharacteristicNotification"+d()); Boolean tTTBoolean = racteristicNotification(characteristic, enabled); n(tTTBoolean+">>>>>>>"); // This is specific to Heart Rate Measurement. if (CLIENT_CHARACTERISTIC_(d())) { BluetoothGattDescriptor descriptor = criptor( ring("00002902-0000-1000-8000-00805f9b34fb")); ue(_NOTIFICATION_VALUE); //ENABLE_NOTIFICATION_VALUE,这里若是没有,可能不能读取数据 escriptor(descriptor); n("setDescriptorover"); } } /** * Retrieves a list of supported GATT services on the connected device. This should be * invoked only after {@code BluetoothGatt#discoverServices()} completes successfully. * * @return A {@code List} of supported services. */ public List if (mBluetoothGatt == null) return null; return vices(); } } 代码直接从Eclipse中复制过来的。 参考了网络资料。
发布者:admin,转转请注明出处:http://www.yc00.com/web/1688676614a161737.html
评论列表(0条)