package com.example.aaaaaaaa;
import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
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.os.Handler;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "BluetoothDemo";
private static final int REQUEST_ENABLE_BT = 1;
private final int REQUEST_PERMISSION_CODE = 1001;
private BluetoothAdapter bluetoothAdapter;
private List<String> deviceList;
private ArrayAdapter<String> deviceListAdapter;
private BluetoothSocket bluetoothSocket;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private Handler handler = new Handler();
private Button btnEnableBluetooth, btnScanDevices, btnConnect, btnDisconnect;
@SuppressLint("MissingPermission")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
deviceList = new ArrayList<>();
deviceListAdapter = new ArrayAdapter<>(this, R.layout.device_item, deviceList);
ListView listView = findViewById(R.id.device_list);
listView.setAdapter(deviceListAdapter);
btnEnableBluetooth = findViewById(R.id.btn_enable_bluetooth);
btnScanDevices = findViewById(R.id.btn_scan_devices);
btnConnect = findViewById(R.id.btn_connect);
btnDisconnect = findViewById(R.id.btn_disconnect);
btnEnableBluetooth.setOnClickListener(v -> enableBluetooth());
btnScanDevices.setOnClickListener(v -> startScanning());
btnConnect.setOnClickListener(v -> connectToDevice());
btnDisconnect.setOnClickListener(v -> disconnectFromDevice());
// 检查权限
initPermission();
}
@SuppressLint("MissingPermission")
private void enableBluetooth() {
if (bluetoothAdapter == null) {
Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
} else if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
Toast.makeText(this, "蓝牙已开启", Toast.LENGTH_SHORT).show();
}
}
@SuppressLint("MissingPermission")
private void startScanning() {
if (bluetoothAdapter.isEnabled()) {
deviceList.clear();
deviceListAdapter.notifyDataSetChanged();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
bluetoothAdapter.startDiscovery();
Toast.makeText(this, "开始扫描蓝牙设备", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "请先开启蓝牙", Toast.LENGTH_SHORT).show();
}
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
@SuppressLint("MissingPermission") String deviceInfo = device.getName() + " - " + device.getAddress();
deviceList.add(deviceInfo);
deviceListAdapter.notifyDataSetChanged();
}
}
};
// Disable Bluetooth
private void disableBluetooth() {
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "BLUETOOTH_CONNECT permission required to disable Bluetooth", Toast.LENGTH_SHORT).show();
return;
}
boolean isDisabled = bluetoothAdapter.disable();
if (isDisabled) {
Toast.makeText(this, "Bluetooth disabled", Toast.LENGTH_SHORT).show();
deviceList.clear();
deviceAdapter.notifyDataSetChanged();
} else {
Toast.makeText(this, "Failed to disable Bluetooth", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Bluetooth is already disabled", Toast.LENGTH_SHORT).show();
}
}
@SuppressLint("MissingPermission")
private void connectToDevice() {
if (deviceList.isEmpty()) {
Toast.makeText(this, "没有发现可用的设备", Toast.LENGTH_SHORT).show();
return;
}
String deviceAddress = deviceList.get(0).split(" - ")[1];
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
new Thread(() -> {
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
bluetoothSocket.connect();
handler.post(() -> Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show());
receiveData();
} catch (IOException e) {
Log.e(TAG, "连接失败", e);
handler.post(() -> Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show());
}
}).start();
}
private void receiveData() {
new Thread(() -> {
try (InputStream inputStream = bluetoothSocket.getInputStream()) {
byte[] buffer = new byte[1024];
int bytes;
while ((bytes = inputStream.read(buffer)) != -1) {
String receivedData = new String(buffer, 0, bytes);
Log.d(TAG, "收到数据: " + receivedData);
}
} catch (IOException e) {
Log.e(TAG, "接收数据时出错", e);
}
}).start();
}
private void disconnectFromDevice() {
try {
if (bluetoothSocket != null) {
bluetoothSocket.close();
Toast.makeText(this, "蓝牙已断开", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Log.e(TAG, "断开连接时出错", e);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
disconnectFromDevice();
}
private void initPermission() {
List<String> mPermissionList = new ArrayList<>();
// Android 版本大于等于 12 时,申请新的蓝牙权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
//根据实际需要申请定位权限
//mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
//mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
} else {
mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
ActivityCompat.requestPermissions(this, mPermissionList.toArray(new String[0]), REQUEST_PERMISSION_CODE);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_CODE) {
boolean allGranted = true;
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
allGranted = false;
break;
}
}
if (allGranted) {
Toast.makeText(this, "所有权限已被授予,可以使用蓝牙", Toast.LENGTH_SHORT).show();
// 可以继续执行蓝牙相关操作
} else {
Toast.makeText(this, "权限未被授予,无法使用蓝牙", Toast.LENGTH_SHORT).show();
finish(); // 或者禁用蓝牙功能
}
// 所有权限被授予,继续执行
}
}
}
Android13实现蓝牙开启关闭、连接等Demo
最新推荐文章于 2025-05-07 18:00:22 发布