android蓝牙4.0使用方法

蓝牙介绍

    Android 4.3(API Level 18)介绍了内置平台支持蓝牙低能量的核心作用,并提供了API,应用程序可以用它来发现设备,查询服务,和读写字符。与传统的蓝牙相比,Bluetooth Low Energy (BLE) 旨在提供显著降低功耗。这使得Android应用能够与具有BLE的低耗能设备进行通信,例如,传感器、心率监视器,健身设备,等等。

BLE 权限

    为了在应用程序中使用蓝牙功能,必须声明蓝牙蓝牙许可。您需要这个权限执行任何蓝牙通信,如请求连接,接受连接,传输数据。 

    声明蓝牙权限需要在应用的manifest 文件中加如下代码:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

 

如果你想声明应用程序仅BLE-capable设备可用,在你的应用程序的清单包括以下: 

<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

然而,如果你想让你的应用程序可用的设备不支持BLE,你应该还是这个元素包含在您的应用程序的清单,但在运行时设置android:required=“false”。在运行时您可以决定BLE可用性通过使用PackageManager.hasSystemFeature(): 

          //用这个检查设备是否支持BLE。
         if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
                     Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
                    finish();
                }

设置BLE

    BLE在您的应用程序可以交互之前,你需要确认在设备上是支持BLE,如果是这样,确保启用。注意这检查需要设置< uses-feature…/ >为false

    如果不支持BLE,那么你应该禁用任何BLE特性。如果支持,但是已经禁用,你可以用你的应用启动它。完成这个设置需要两步,使用BluetoothAdapter

1.获取luetoothAdapter。

    BluetoothAdapter代表设备的蓝牙适配器。整个系统有一个蓝牙适配器,和您的应用程序可以使用这个对象与它交互。下面的代码片段显示了如何获取适配器。使用getSystemService ()返回一个BluetoothManager实例,然后获取适配器。

Android 4.3(API LEVEL 18)引入了BluetoothManager:

//初始化蓝牙适配器
final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

2.启动蓝牙

   接下来,您需要确保启用蓝牙。用isEnabled()检查蓝牙当前是否启动。如果这个方法返回false,那么蓝牙是关闭的。下面的代码片段检查是否启用蓝牙。如果没有,将提示用户去设置启用蓝牙。


if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

 

搜索蓝牙设备

  搜索蓝牙设备使用startLeScan()方法。该方法以BluetoothAdapter.LeScanCallback作为参数,您必须实现这个回调,因为这是如何返回扫描结果。因为扫描非常耗电,你应该遵守如下规则:

· 只要找到了设备就应该停止搜索。

· 不要在一个无限循环中搜索, 需要设置一个时间限制搜索. 

 

下面代码作用是如何开始和结束搜索:

 

 


public class DeviceScanActivity extends ListActivity {

    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;

    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    ...
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            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),提供一个UUID对象数组,指定蓝牙服务应用程序所支持的。 

    这里使用BluetoothAdapter.LeScanCallback的实现用来显示蓝牙扫描结果:

private LeDeviceListAdapter mLeDeviceListAdapter;
...
// Device scan callback.
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();
           }
       });
   }
};

注意:不能在同一时间扫描BLE和传统的蓝牙。

链接 GATT Server

      BLE设备交互的第一步是连接到它,更具体地说,连接到设备上的GATT服务器。连接到GATT服务器使用connectGatt()方法,这个方法取三个参数:一个上下文对象,(布尔指示是否自动连接到设备就可用),和BluetoothGattCallback回调函数。

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

    这个连接到GATT服务端通过BLE设备,并返回一个BluetoothGatt实例,然后您可以使用GATT客户端进行操作。调用者(Android应用程序)是GATT客户端。BluetoothGattCallback用于提供结果给客户端,如连接状态,以及任何进一步的GATT客户端操作。

     在这个例子中,有幸获得应用程序提供了一个活动(DeviceControlActivity)连接,显示数据,并显示GATT服务和支持的设备特征。基于用户输入,此活动与一个服务交互称为BluetoothLeService,服务与BLE设备交互是通过Android BLE API:

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

    // Various callback methods defined by the 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, "Connected to GATT server.");
                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
        // 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()辅助方法并将其传递一个action。注意,本节中的数据解析执行按照蓝牙心率测量概要文件规范:

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

    // This is special handling for the Heart Rate Measurement profile. Data
    // parsing is carried out as per profile specifications.
    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 {
        // For all other profiles, writes the data formatted in HEX.
        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);
}

Back in DeviceControlActivity, these events are handled by a BroadcastReceiver:

// 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 = 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)) {
            // Show all the supported services and characteristics on the
            // user interface.
            displayGattServices(mBluetoothLeService.getSupportedGattServices());
        } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
        }
    }
};

 

阅读BLE属性 

    一旦你的Android应用程序连接到一个GATT服务器和发现服务,它可以读取和写入属性。例如,这段代码遍历服务器的服务和数据并将它们显示在UI:

public class DeviceControlActivity extends Activity {
    ...
    // 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;
        String unknownServiceString = getResources().
                getString(R.string.unknown_service);
        String unknownCharaString = getResources().
                getString(R.string.unknown_characteristic);
        ArrayList<HashMap<String, String>> gattServiceData =
                new ArrayList<HashMap<String, String>>();
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
                = new ArrayList<ArrayList<HashMap<String, String>>>();
        mGattCharacteristics =
                new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            HashMap<String, String> currentServiceData =
                    new HashMap<String, String>();
            uuid = gattService.getUuid().toString();
            currentServiceData.put(
                    LIST_NAME, SampleGattAttributes.
                            lookup(uuid, unknownServiceString));
            currentServiceData.put(LIST_UUID, uuid);
            gattServiceData.add(currentServiceData);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
                    new ArrayList<HashMap<String, String>>();
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas =
                    new ArrayList<BluetoothGattCharacteristic>();
           // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic :
                    gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData =
                        new HashMap<String, String>();
                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);
         }
    ...
    }
...
}

接收GATT通知

   当一个特定的设备上的特征变化需要BLE的应用通知。这个代码片段显示了如何设置一个通知特性,使用setCharacteristicNotification()方法:

 

 

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

     一旦通知作为一个特性被启用,如果远程设备上的特性变化将触发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://www.mzph.cn/news/419411.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java基础面试题整理(BAT)

转载自&#xff1a;http://www.nowcoder.com/discuss/5949?type2&order0&pos23&page5点击打开链接 在阿里面试之前总结了一下内推同学的面经&#xff0c;把面试题总结到一块&#xff0c;并进行了分类。有些题目我也总结了一下答案&#xff0c;大家可以参考一下&am…

Android中设置输入法为数字输入

1.对于用XML布局的EditText 使用setInputType(EditorInfo.TYPE_CLASS_NUMBER); 2.对于用Java代码生成EditText 使用setInputType(EditorInfo.TYPE_CLASS_NUMBER); setKeyListener(new DigitsKeyListener(false,true));

n个数里找出前m个数(或者 从10亿个浮点数中找出最大的1万个)

转载自&#xff1a;http://blog.csdn.net/winsunxu/article/details/6219376点击打开链接 引子 每年十一月各大IT公司都不约而同、争后恐后地到各大高校进行全国巡回招聘。与此同时&#xff0c;网上也开始出现大量笔试面试题&#xff1b;网上流传的题目往往都很精巧&#xff0c…

poj_3977 折半枚举

题目大意 给定N&#xff08;N<35)个数字&#xff0c;每个数字都< 2^15. 其中一个或多个数字加和可以得到s&#xff0c;求出s的绝对值的最小值&#xff0c;并给出当s取绝对值最小值时&#xff0c;需要加和的数字的个数。 题目分析 需要枚举集合的所有情况&#xff0c;2^35…

Android 应用更新和在服务器下载android应用

下载android应用有两种表现形式&#xff1a;一种是交给Android系统的下载管理器;另一种是自己去监控下载。 1.使用Android下载管理器下载应用并安装 public class UpdateService extends Service {// 安卓系统下载管理类DownloadManager manager;// 接收下载完的广播DownloadCo…

Linux如何查看进程、杀死进程、启动进程等常用命令

转载自&#xff1a;http://blog.csdn.net/wojiaopanpan/article/details/7286430/ 关键字: linux 查进程、杀进程、起进程 1.查进程 ps命令查找与进程相关的PID号&#xff1a; ps a 显示现行终端机下的所有程序&#xff0c;包括其他用户的程序。 ps -A 显示所有程…

(原创)c#学习笔记06--函数02--变量的作用域01--其他结构中变量的作用域

6.2 变量的作用域 在上一节中&#xff0c;读者可能想知道为什么需要利用函数交换数据。原因是C#中的变量仅能从代码的本地作用域访问。给定的变量有一个作用域&#xff0c;访问该变量要通过这个作用域来实现。 在上一节中&#xff0c;读者可能想知道为什么需要利用函数交换数据…

禁用应用中Android系统的导航栏(特别是平板)

由于公司项目是在全屏下的&#xff0c;所有界面都是全屏&#xff0c;唯有弹出提示框的时候&#xff0c;会出现系统的导航栏&#xff0c;由于是平板&#xff0c;导航栏信息比较多&#xff0c;该项目属于永不让用户进入原系统的项目。所以有导航栏&#xff0c;就让用户有了机会进…

spring使用注解@Scheduled执行定时任务

最近做的项目中遇到了用spring中Schedule注解执行定时任务的功能&#xff0c;这里简单记录一下。 首先在applicationContext.xml中进行配置&#xff1a; xmlns 加下面的内容 xsi:schemaLocation加下面的内容 最后我们的task任务扫描注解 需要注意的几点&#xff1a; 1、spring的…

关于dialog的一点东西

今天开发一个上传照片的小功能&#xff0c;对弹出的Dialog的一些用法查找了下&#xff0c;记录下来以后备用。 1.设置dialog标题居中: 在style中配置如下代码 <style name"UploadDialog" parent"android:style/Theme.Dialog"> <item …

DIY Ruby CPU 分析 Part II

【编者按】作者 Emil Soman&#xff0c;Rubyist&#xff0c;除此之外竟然同时也是艺术家&#xff0c;吉他手&#xff0c;Garden City RubyConf 组织者。本文是 DIY Ruby CPU Profiling 的第二部分。本文系 OneAPM 工程师编译整理。 在第一部分中我们学习了 CPU 分析的含义和进行…

spring注解 @Scheduled(cron = 0 0 1 * * *)的使用来实现定时的执行任务

<span style"font-size:14px;">初次接触定时类的小程序&#xff0c;还是走了很多的弯路&#xff0c;如今终于搞定了&#xff0c;总结如下&#xff1a;</span> <span style"font-size:14px;">import com.activityvip.api.service.Securit…

在Oracle里,表的别名不能用as,列的别名可以用as

列的别名也可以不用as&#xff0c;如&#xff1a;select t.a xxx from table t在Oracle数据库中&#xff0c;数据表别名是不能加as的&#xff0c;例如&#xff1a; select a.appname from appinfo a;-- 正确 select a.appname from appinfo as a;-- 错误 注释&#xff1a;这…

Android自定义RadioButton

今天公司项目中需要完成一个效果&#xff0c;首先是要用自己的图片&#xff0c;然后文字在按钮图片的左边。 1.使文字在图片的左边&#xff0c;有两种方法&#xff1a; 第一种&#xff0c;设置radioButton的属性&#xff1a; <span style"font-size:24px;">a…

MySQL实现当前数据表的所有时间都增加或减少指定的时间间隔

做了一个简答的小项目&#xff0c;其中遇到了一些数据库的sql使用技巧总结如下&#xff1a; DATE_ADD() 函数向日期添加指定的时间间隔。 当前表所有数据都往后增加一天时间&#xff1a; UPDATE ACT_BlockNum SET CreateTime DATE_ADD(CreateTime, INTERVAL 1 DAY); 当前…

Android蓝牙4.0的数据通讯

我在两家公司都用到了app与BLE设备通讯&#xff0c;当时也是什么都不懂&#xff0c;在网上各种搜索&#xff0c;各种查资料&#xff0c;总算弄出来了。在这里记录下来&#xff0c;希望对有需要的人有些帮助。 1.检测手机是否支持蓝牙4.0&#xff08;一般手机4.3以上的android系…