大家好,又见面了,我是你们的朋友全栈君。
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
BluetoothAdapter bTAdatper = BluetoothAdapter.getDefaultAdapter();
if(bTAdatper==null){
Toast.makeText(this,"当前设备不支持蓝牙功能",Toast.LENGTH_SHORT).show();
}
if(!bTAdatper.isEnabled()){
/* Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(i);*/
bTAdatper.enable();
}
//开启被其它蓝牙设备发现的功能
if (bTAdatper.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//设置为一直开启
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(i);
}
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0); 最后的参数设置为0,可以让蓝牙设备一直处于可发现状态。当我们需要设置具体可被发现的时间时,最多只能设置300秒。 i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
mBluetoothAdapter.startDiscovery();
mBluetoothAdapter.cancelDiscovery()
BluetoothAdapter.ACTION_DISCOVERY_STARTED、
BluetoothDevice.ACTION_FOUND、
BluetoothAdapter.ACTION_DISCOVERY_FINISHED。
这三个分别对应开始搜索、搜索到设备、搜索结束。因此,我们可以定义一个广播,来获取这些状态。
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//避免重复添加已经绑定过的设备
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
//此处的adapter是列表的adapter,不是BluetoothAdapter
adapter.add(device);
adapter.notifyDataSetChanged();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(MainActivity.this,"开始搜索",Toast.LENGTH_SHORT).show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(MainActivity.this,"搜索完毕",Toast.LENGTH_SHORT).show();
}
}
};
if (device.getBondState() != BluetoothDevice.BOND_BONDED) 系统会保存之前配对过的蓝牙设备,这里我们对搜索到的设备进行过滤,判断是否设备是否已经配对过。因此,我们还可以直接获取之前配对过的设备。
Set<BluetoothDevice> pairedDevices = bTAdatper.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
adapter.add(device);
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/159847.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有