Android Developer -- Bluetooth篇 开发实例之一
Posted H_bolin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Developer -- Bluetooth篇 开发实例之一相关的知识,希望对你有一定的参考价值。
第一步:声明Bluetooth Permissions
<!-- 设置蓝牙访问权限 --> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
第二步:获取BluetoothAdapter,判断该设备是否支持蓝牙
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth // 说明该设备不支持蓝牙 }
第三步:检查当前的蓝牙是否开启
if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); // 不做提示,强行打开 // mAdapter.enable(); }
如果是第一种方式:会出现提示弹窗
A dialog will appear requesting user permission to enable Bluetooth, as shown in Figure 1. If the user responds "Yes," the system will begin to enable Bluetooth and focus will return to your application once the process completes (or fails).
If enabling Bluetooth succeeds, your Activity will receive the RESULT_OK
result code in the onActivityResult()
callback. If Bluetooth was not enabled due to an error (or the user responded "No") then the result code will be RESULT_CANCELED
.
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == RESULT_OK) { // 蓝牙已经开启 Log.d("h_bl", "蓝牙已经开启完毕"); String bluetoothName = bluetoothAdapter.getName(); // 获取本地蓝牙名称 String bluetoothAddress = bluetoothAdapter.getAddress(); // 获取本地蓝牙地址 tv_bluetoothName.append(bluetoothName); tv_bluetoothAddress.append(bluetoothAddress); } else { Log.d("h_bl", "蓝牙开启失败"); } } super.onActivityResult(requestCode, resultCode, data); }
其中,
private int REQUEST_ENABLE_BT = 1; // 蓝牙打开的请求码
Optionally, your application can also listen for the ACTION_STATE_CHANGED
broadcast Intent, which the system will broadcast whenever the Bluetooth state has changed. This broadcast contains the extra fields EXTRA_STATE
and EXTRA_PREVIOUS_STATE
, containing the new and old Bluetooth states, respectively. Possible values for these extra fields areSTATE_TURNING_ON
, STATE_ON
, STATE_TURNING_OFF
, and STATE_OFF
. Listening for this broadcast can be useful to detect changes made to the Bluetooth state while your app is running.
可选的,你的应用可以监听ACTION_STATE_CHANGED广播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.
提示:启用程序会自动启用蓝牙。如果你打算开启设备的可见性,可以跳过上面的2步。阅读关于启用可发现,下面。 --- 设置蓝牙的可见性
第四步:寻找其他设备
使用BluetoothAdapter,你能够打开可见性的设备(搜索到的蓝牙设备)和已经配对的的设备列表。
记住配对和连接之间的区别,已经配对的意味着两个设备是互相认识对方的存在,已经有了一个用来认证的共享的key,然后可以被捕捉对于建立一个可信的连接互相。
4.1 找到已经配对的设备
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { Toast.makeText(getApplicationContext(), "没有找到已匹对的设备!", Toast.LENGTH_SHORT).show(); }
4.2 发现设备
调用startDiscovery()函数后,系统将扫描12秒,返回找到的蓝牙设备。我们需用广播来接收。
For each device, the system will broadcast the ACTION_FOUND
Intent. This Intent carries the extra fields EXTRA_DEVICE
and EXTRA_CLASS
, containing a BluetoothDevice
and a BluetoothClass
, respectively. For example, here‘s how you can register to handle the broadcast when devices are discovered:
每发现一个设备,系统就会发送ACTION_FOUND
Intent.的广播,这个Intent携带额外的字段EXTRA_DEVICE
and EXTRA_CLASS,包含a
BluetoothDevice
and a BluetoothClass。
// Create a BroadcastReceiver for ACTION_FOUND private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // Add the name and address to an array adapter to show in a ListView mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } }; // Register the BroadcastReceiver IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); // Don‘t forget to unregister during onDestroy
其中,需要调用
// 扫描蓝牙设备 btAdapter.startDiscovery();
注意:Once you have found a device to connect, be certain that you always stop discovery with cancelDiscovery()
before attempting a connection。
连接设备之前,要调用cancelDiscovery(),以便节约资源。
另外,需要取消广播:
@Override protected void onDestroy() { unregisterReceiver(mReceiver); super.onDestroy(); }
第五步:设备的可发现时间设定,默认是120S。
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent);
以上是关于Android Developer -- Bluetooth篇 开发实例之一的主要内容,如果未能解决你的问题,请参考以下文章
Android Make Disappear or remove the blue dot on the map v2
source.android.google && developer.android.google