您的位置:首页 > 移动开发 > Android开发

Android 蓝牙开发(二)开启蓝牙,获取状态,发现设备。

2015-09-23 16:47 615 查看
(1)获取蓝牙相关权限。

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
(2)获取蓝牙状态。

   获取蓝牙适配器:

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    查看当前设备是否支持蓝牙:

if(bluetoothAdapter == null){
//("本机不支持蓝牙");
return;
}

  查看蓝牙是否已经打开:
if(!bluetoothAdapter.isEnabled()){
//("本机蓝牙未打开");
}

(3)打开蓝牙。
启用Intent,让系统开启蓝牙:

Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent , REQUEST_ENABLE_BLUETOOTH);

在ActivityResult中处理结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == REQUEST_ENABLE_BLUETOOTH){
//("蓝牙打开成功 ");

}
}(4)让本机蓝牙可以被其他蓝牙设备发现:
 if(bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION , 300);
startActivity(discoverableIntent);
//("本机蓝牙 300 秒内可见");
}(5)查看已经配对过的蓝牙设备。
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
if(devices.size() > 0){
//处理
}
(6)开启发现周边蓝牙设备。
使用 adapter.startDiscovery() 方法来搜索设备,通过注册蓝牙相关广播监听,来获取和处理搜索结果。

相关监听广播有:IntentFilter foundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//发现蓝牙设备后的广播
IntentFilter startedFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);//开始搜索的广播
IntentFilter finishedFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//搜索结束后的广播
当搜索到附近可用蓝牙设备后,通过:

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);获取设备相关信息,如:
device.getName() //设备名称
device.getAddress() //地址:如E3:34:23:D3:E2:98
device.getBondState() // 设备的绑定状态
device.getType() //设备的类型
device.getBluetoothClass() // BluetoothClass
device.getUuids() //uuid组

本文 Github 地址: https://github.com/huntervwang/BluetoothDemo
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: