1、如何获取蓝牙适配器,以及打开蓝牙,判断本机是否拥有蓝牙等
首先不要忘了给权限哟
// 设置监听器
myButton.setOnClickListener(new View.OnClickListener() {
// 获得蓝牙适配器
// 因为目前手机只支持一个蓝牙,所以该对象不能自己创建哟
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 判断本机是否拥有蓝牙
if (adapter != null) {
System.out.println("本机拥有蓝牙");
// 判断蓝牙是否打开
if (!adapter.isEnabled()) {
// 创建一个intent对象,该对象启动一个activity,提示用户开启蓝牙设备
Intent intent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
// 启动intent对象
startActivity(intent);
}
// 得到所有已经配对的蓝牙适配器对象
Set<BluetoothDevice> devices = adapter.getBondedDevices();
if (devices.size() > 0) {
// 迭代
for (BluetoothDevice de : adapter.getBondedDevices()) {
System.out.println(de.getAddress());
}
} else {
System.out.println("还没有配对");
}
} else {
System.out.println("本机没有蓝牙");
}
}
});
2、如何获取搜索到的周围的蓝牙设备
每当搜索到周围的一个蓝牙设备时,系统会发出一个广播,所以我们首先要做的是接受并处理这个广播
先继承BroadcastReceiver类,实现自己想要处理的动作
// 接受到广播后的处理
//必须要继承BroadcastReceiver
class BluetoothReceiver extends BroadcastReceiver {
//Context 表示从哪个Activity传过来的
//Intent 可以接受到传过来的数据等
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
//getAction()方法返回这个广播的广播常量,你可以根据它来判断这个广播是否是你要接受的
//String action = intent.getAction();
//if(BluetoothDevice.ACTION_FOUND.equals(action))
//获取BluetoothDevice对象
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//打印远程蓝牙设备的MAC地址
System.out.println(device.getAddress());
//打印远程蓝牙设备的名称
System.out.println("name:" + device.getName());
//取消蓝牙搜索
bluetoothadapter.cancelDiscovery();
}
}
3、动态绑定“过滤器”
// 实例化处理广播这个类
BluetoothReceiver bluetoothReceiver = new BluetoothReceiver();
// 创建一个广播“过滤器”
IntentFilter intentFilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
// 绑定“过滤器”
registerReceiver(bluetoothReceiver, intentFilter);
4、开始搜索周围蓝牙设备
// 扫描周围的蓝牙适配器
// 注意,这是异步的哟
bluetoothadapter.startDiscovery();
5、修改蓝牙设备可见性
// 修改蓝牙设备可见性,监听器
class DiscoverButtonListener implements View.OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 创建一个intent,请求将蓝牙适配器设置为可见状态
Intent discoverIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
// 添加一个信息,设置可见状态持续时间
discoverIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
// 启动Activity,系统自带的Activity
startActivity(discoverIntent);
}
}