android bluetooth开发基础-4设置蓝牙
来源:互联网 发布:关闭多台linux系统脚本 编辑:程序博客网 时间:2024/04/30 17:36
在你的应用程序使用蓝牙进行通信之前,你需要确认你的设备支持蓝牙,如果支持,那么确认它已被启动。
如果你的设备不支持蓝牙,那么你应该关闭任何蓝牙特性。如果蓝牙被支持,那么你可以在你的程序中要求用户启动蓝牙。这需要两个步骤,并且要使用BluetoothAdapter这个类。
如果你的设备不支持蓝牙,那么要关闭任何蓝牙功能。如果支持蓝牙但没有启动,则你可以在程序中要求用户启动蓝牙。启动蓝牙需要两个步骤,并且需要BluetoothAdapter类。
- 获得BluetoothAdapter类
任何蓝牙activity都需要BluetoothAdapter类。使用静态方法getDefaultAdapter()获得一个BluetoothAdapter的实例,这代表了设备本身的蓝牙适配器(the Bluetooth radio)。整个系统只有一个蓝牙适配器,你的程序可以通过获取到BluetoothAdapter实例与之交互。如果getDefaultAdapter()方法返回null则说明你的设备不支持蓝牙。
示例代码如下:
- BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();if (mBluetoothAdapter == null) { // Device does not support Bluetooth}
2.启动蓝牙
接下来,你必须确保用户启动了蓝牙。调用isEnabled()方法来检查当前蓝牙是否启动。如果该方法返回false,那么说明蓝牙没有启动。这时需要使用“ACTION_REQUEST_ENABLE”action Intent作为参数,调用startActivityForResult()方法来请求启动蓝牙。这将通过系统设备来发出启动蓝牙的请求(不会停止你的程序)。例如:
- if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);}
执行如上的代码将会弹出一个对话框,请求启动蓝牙的用户权限,如Figure 1所示。如果用户点击“Yes”按钮,那么系统将开始启动蓝牙,启动蓝牙(有可能失败)之后你的程序将重新获得焦点。
如果启动蓝牙成功,你的Activity将在onActivityResult()回调函数中接收到一个RESULT_OK结果码。如果蓝牙启动失败或者用户不允许启动蓝牙,则会收到RESULT_CANCELED。
可选的,你的程序能够监听ACTION_STATE_CHANGED broadcast Intent,这个广播Intent是系统探测到蓝牙状态改变时发出的。这个广播Intent包含了EXTRA_STATE和EXTRA_PREVIOUS_STATE两个域,包含了蓝牙旧的和新的状态。这两个域的值可能是STATE_TURNING_ON,STATE_ON,STATE_TURNING_OFF和STATE_OFF。
Tip: Enabling discoverability will automatically enable Bluetooth. If you plan to consistently enable device discoverability before performing Bluetooth activity, you can skip step 2 above. Read about enabling discoverability, below.
- android bluetooth开发基础-4设置蓝牙
- Android中的蓝牙Bluetooth应用开发基础
- android Bluetooth蓝牙开发
- Android --- Bluetooth(基础蓝牙)
- Android Bluetooth蓝牙开发:Bluetooth蓝牙设备之间数据传输(4)
- Android Bluetooth蓝牙开发:发现Bluetooth蓝牙设备(1)
- Bluetooth--- android -- 蓝牙 bluetooth
- BlueTooth Android开发基础
- Android Bluetooth蓝牙开发\蓝牙协议\蓝牙通信
- Android bluetooth 蓝牙开发/蓝牙协议/蓝牙通信
- Bluetooth---如何使用Android蓝牙开发
- Bluetooth--- Android 蓝牙开发基本流程
- Android Bluetooth蓝牙开发(一)
- Android Bluetooth蓝牙开发(二)
- Android Bluetooth蓝牙开发(三)
- Bluetooth---如何使用Android蓝牙开发
- # Android Bluetooth(蓝牙)开发总结
- Android开发之蓝牙(Bluetooth)
- ubuntu 13.10配置root登录
- 在VS调试的时候出现如下错误,生成下面的模块时,启用了优化或没有调试信息;
- android 语音播报(通过手说tts 实现中文语音播报)
- 关于面试常见的一个数组中找出出现一次的几个数字的问题
- Java线程:大总结
- android bluetooth开发基础-4设置蓝牙
- sqlite3使用简介
- 数据类型转换(static_cast, const_cast ,reinterpret_cast ,dynamic_cast )
- error C2381: “exit” : 重定义;__declspec(noreturn) 不同
- log4j.properties配置详解
- 关于android几种常见的UI综合
- 数据库运维常用命令
- jQuery操作Select下拉框标签的一些方法和属性整理
- Android路径中提取文件名