目录
蓝牙连接分为经典蓝牙和低功耗蓝牙,此篇为经典蓝牙。Android Studio 官方指导文件对于两种蓝牙连接都有详细的讲解。地址为:蓝牙概览 | Android 开发者 | Android Developers (google.cn)
一.具体实现
1.向系统获取蓝牙,并判断设备是否支持蓝牙功能。通过 mBluetoothAdapter 对象实现蓝牙的相关功能。
//对象声明
private BluetoothAdapter mBluetoothAdapter;
//蓝牙获取
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//判断 mBluetoothAdapter 是否获取成功
if (mBluetoothAdapter == null) {
Log.e(TAG, "onCreate: 此设备不支持蓝牙");
}
2.判断设备蓝牙是否打开,没有则请求打开蓝牙。
//判断蓝牙是否打开 true为打开
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
3.查询已配对的设备
此功能会获取所有之前设备配对过且没有删除的设备信息。此功能可以快速查看需要连接的设备是否已经处于了已检测到状态,从而可以直接实现连接。
在此方法中可以看到,我是通过动态添加按钮的方式将已连接过的设备信息进行了输出,并对按钮添加了监听事件,从而实现点击选择指定设备进行连接。
private void checkpairedDevices() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
LinearLayout layout2=(LinearLayout) findViewById(R.id.myLinearLayout2);
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
//将连接过的设备信息输出
Log.i("已连接过的设备:", deviceName+"---"+deviceHardwareAddress);
//以下是根据自己的需要对设备信息进行的处理
Button button=new Button(this);
button.setText(deviceName+"_: "+deviceHardwareAddress);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//点击进行连接
connectThread=new ConnectThread(device);
connectThread.run();
}
});
layout2.addView(button);
}
}
}
4.蓝牙扫描
需要注意,蓝牙扫描之前必须开启GPS才能成功扫描,且蓝牙扫描需要注册广播,应用必须针对 ACTION_FOUND
Intent 注册一个 BroadcastReceiver,以便接收每台发现的设备的相关信息。
蓝牙扫描实现:
private void Bluetoothscan() {
//发现设备,实现扫描功能
boolean f = mBluetoothAdapter.startDiscovery();
if (f == true) {
Log.i(TAG, "成功进行扫描以发现设备");
} else {
Log.i(TAG, "扫描失败");
}
}
申请打开GPS,申请打开GPS的方法有很多,此处列举我使用过的两种方法:
方法1:
protected void onCreate(Bundle savedInstanceState) {
//打开GPS的权限申请
List<String> permissionList = new ArrayList<>();
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (!permissionList.isEmpty()) {
String[] permissions = permissionList.toArray(new String[permissionList.size()]);
ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
}
......
}
方法2:
public void GPS() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean isEnabled = loca