项目下载地址github:
1.打开蓝牙:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
/**如果本地蓝牙没有开启,则开启*/
if (!mBluetoothAdapter.isEnabled()) {
// 我们通过startActivityForResult()方法发起的Intent将会在onActivityResult()回调方法中获取用户的选择,比如用户单击了Yes开启,
// 那么将会收到RESULT_OK的结果,
// 如果RESULT_CANCELED则代表用户不愿意开启蓝牙
Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(mIntent, ENABLE_BLUE);
} else {
Toast.makeText(this, "蓝牙已开启", Toast.LENGTH_SHORT).show();
}
监听打开的结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENABLE_BLUE) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "蓝牙开启成功", Toast.LENGTH_SHORT).show();
getBondedDevices();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "蓝牙开始失败", Toast.LENGTH_SHORT).show();
}
} else {
}
}
2.关闭蓝牙:
/**关闭蓝牙*/
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
3.设计蓝牙为可见:
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 180);//180可见时间
startActivity(intent);
4.收索蓝牙:
注册广播监听搜索的结果:
/**注册搜索蓝牙receiver*/
mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
mFilter.addAction(BluetoothDevice.ACTION_FOUND);
mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mReceiver, mFilter);
开始的搜索:
// 如果正在搜索,就先取消搜索
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
// 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回