1、Androidmanifest.xml文件
加入需要添加的权限配置
<!--开启蓝牙需要的配置-->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 蓝牙权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- google在android6.0之后,为了更好的保护用户的数据安全,所有需要访问硬件唯一标识符的地方都需要申请位置权限 -->
<!-- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
MainActivity.java
package com.example.study;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* android 连接 蓝牙 (配置)
*/
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
// 拿到 BluetoothAdapter
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> deviceListAdapter;
private ListView deviceListView;
private BluetoothDevice selectedDevice;
private BluetoothSocket bluetoothSocket;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
createBluetoothBond();
registerBroadcast();
}
// 初始化
private void init() {
// 获取蓝牙配置器 BluetoothAdapter
BluetoothManager bluetoothManger =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManger.getAdapter();
}
// 蓝牙配对
@RequiresApi(api = Build.VERSION_CODES.M)
@SuppressLint("MissingPermission")
private void createBluetoothBond() {
if (bluetoothAdapter == null) {
Toast.makeText(this, "没有蓝牙功能", Toast.LENGTH_SHORT).show();
return;
}
if (!bluetoothAdapter.isEnabled()) {
// 没有开启蓝牙 开启蓝牙
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//判断是否有访问位置的权限,没有权限,直接申请位置权限
if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
}
// 创建设备列表适配器
deviceListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
deviceListView = (ListView) findViewById(R.id.device_list);
deviceListView.setAdapter(deviceListAdapter);
deviceListView.setOnItemClickListener((adapterView, view, i, l) -> {
String deviceName = deviceListAdapter.getItem(i);
selectedDevice = bluetoothAdapter.getRemoteDevice(deviceName.split("\\n")[1]);
connectToDevice(selectedDevice);
});
// 搜索设备按钮点击事件
Button searchButton = (Button) findViewById(R.id.search_button);
searchButton.setOnClickListener(view -> {
startDeviceDiscovery();
});
}
@SuppressLint("MissingPermission")
private void startDeviceDiscovery() {
deviceListAdapter.clear();
bluetoothAdapter.startDiscovery();
// Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
// for (BluetoothDevice bondedDevice : bondedDevices) {
// System.out.println("bondedDevice" + bondedDevice.getName());
//
// }
}
@SuppressLint("MissingPermission")
private void connectToDevice(BluetoothDevice device) {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // SPP UUID for serial communication
try {
// 进行配对
if (!(device.getBondState() == BluetoothDevice.BOND_BONDED)) {
device.createBond();
}
// 等待配对完成
Thread.sleep(500);
bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid);
bluetoothSocket.connect();
System.out.println("111");
// 成功连接
// 连接成功后可以进行数据读写
// readFromBluetooth();
// writeToBluetooth("Hello, Bluetooth!");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
@SuppressLint("MissingPermission")
private final BroadcastReceiver deviceReceiver = 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);
deviceListAdapter.add(device.getName() + "\n" + device.getAddress());
deviceListAdapter.notifyDataSetChanged();
}
// 做配对使用
else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int pairingVariant = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);
// 如果需要 PIN 码,可以在这里自动输入
if (pairingVariant == BluetoothDevice.PAIRING_VARIANT_PIN) {
device.setPin("1234".getBytes()); // 替换为您的 PIN 码
}
// 如果需要用户确认配对请求,可以在这里显示对话框来请求用户确认
}
else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
int previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
// 配对状态改变的处理逻辑
if (bondState == BluetoothDevice.BOND_BONDED && previousBondState == BluetoothDevice.BOND_BONDING) {
// 配对成功
} else if (bondState == BluetoothDevice.BOND_NONE && previousBondState == BluetoothDevice.BOND_BONDED) {
// 配对解除
}
}
}
};
// 注册广播
public void registerBroadcast() {
// 注册广播接收器
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);//搜索发现设备
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变
intent.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//行动扫描模式改变了
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//动作状态发生了变化
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(deviceReceiver, intent);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
// 取消注册广播接收器
unregisterReceiver(deviceReceiver);
}
// todo 蓝牙动态申请权限
private void initPermission() {
HashSet<String> mPermissionList = new HashSet<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// Android 版本大于等于 Android12 时
// 只包括蓝牙这部分的权限,其余的需要什么权限自己添加
mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
mPermissionList.add(Manifest.permission.BLUETOOTH_ADMIN);
} else {
// Android 版本小于 Android12 及以下版本
mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (mPermissionList.size() > 0) {
ActivityCompat.requestPermissions(this, mPermissionList.toArray(new String[0]), 1001);
}
}
/*
this method is required for all devices running API 23+ (Android 6.0 + )
Android must programmatically check the permission for bluetooth
only put permission in manifest is not enough
Note: this will only execute on version > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermission() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
int permissionCheck = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
}, 1001); //any number
}
}
}
}
private boolean checkPermissions() {
//本app需要以下权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH}, 0);
System.out.println("-------已经申请了蓝牙权限1------");
} else {
System.out.println("-------已经拥有了蓝牙权限权限1------");
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_ADMIN}, 0);
System.out.println("-------已经申请了蓝牙权限2------");
} else {
System.out.println("-------已经拥有了蓝牙权限权限2------");
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
System.out.println("-------已经申请了定位权限1------");
} else {
System.out.println("-------已经拥有了定位权限1------");
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
System.out.println("-------已经申请了定位权限2------");
} else {
System.out.println("-------已经拥有了定位权限2------");
}
return true;
}
}