1.声明权限
2.获取本地蓝牙适配器
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
3.打开本地蓝牙
打开蓝牙有2中打开方式
1.第一种(强行打开)
bluetoothAdapter.enable();
2.第二种(调用系统Api打开)
private static final int EXQUEAT_OPEN = 1;
Intent open = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(open, EXQUEAT_OPEN);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (EXQUEAT_OPEN == requestCode) {
if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "打开蓝牙失败", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "打开蓝牙成功", Toast.LENGTH_SHORT).show();
}
}
}
4.关闭本地蓝牙
bluetoothAdapter.disable();
//开启被其它蓝牙设备发现的功能
if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//设置为一直开启
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(i);
}
//获取名字 mac地址
String name = bluetoothAdapter.getName();
String mac = bluetoothAdapter.getAddress();
//获取当前蓝牙的状态、
int state = bluetoothAdapter.getState();
switch (state) {
case BluetoothAdapter.STATE_ON:
Toast.makeText(this, "蓝牙已经打开", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.STATE_TURNING_ON:
Toast.makeText(this, "蓝牙正在打开。。", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Toast.makeText(this, "蓝牙正在关闭。。", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.STATE_OFF:
Toast.makeText(this, "蓝牙已经关闭", Toast.LENGTH_SHORT).show();
break;
}
(二)搜索蓝牙设备并展示:https://blog.csdn.net/lumingzhang/article/details/89922235
(三)蓝牙设备连接及通信:https://blog.csdn.net/lumingzhang/article/details/89922252