Android开发——蓝牙与外部设备连接

本文详细介绍了如何在Android应用中获取蓝牙权限,检测设备支持情况,申请权限,寻找特定设备以及实现数据传输的过程。
摘要由CSDN通过智能技术生成

一、获取蓝牙权限

在Manifest.xml文件中添加蓝牙权限声明

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <!--开启蓝牙权限-->
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE"/>
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.Dfbbbb"
        tools:targetApi="31">
        <activity
            android:name=".ForbiddenActivity"
            android:exported="false" />
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

二、检查设备是否支持蓝牙

BluetoothAdapter defaultAdapter = BluetoothAdapter.getDefaultAdapter();
if (defaultAdapter == null) {
    Toast.makeText(MainActivity.this, "该设备不支持蓝牙", Toast.LENGTH_SHORT).show();
}

三、申请蓝牙权限

if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
    // TODO: Consider calling
    //    ActivityCompat#requestPermissions
    // here to request the missing permissions, and then overriding
    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
    //                                          int[] grantResults)
    // to handle the case where the user grants the permission. See the documentation
    // for ActivityCompat#requestPermissions for more details.
    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.BLUETOOTH_CONNECT},REQUEST_BLUETOOTH_PERMISSION);
}

四、寻找目标设备

Set<BluetoothDevice> bondedDevices = defaultAdapter.getBondedDevices();
BluetoothDevice targetDevice = null;
if (bondedDevices.size() > 0) {
    for (BluetoothDevice device:bondedDevices){
        if (device.getName().equals("目标设备名称")){
            targetDevice=device;
            break;
        }
    }
}

五、数据传输

BluetoothSocket bluetoothSocket = null;
InputStream inputStream = null;
byte[] buffer = new byte[1024];
int bytes;
try {
    bluetoothSocket = targetDevice.createRfcommSocketToServiceRecord(UUID.fromString("这个 UUID 需要与外部设备的蓝牙协议一致"));
    bluetoothSocket.connect();
    inputStream = bluetoothSocket.getInputStream();
} catch (IOException e) {
    throw new RuntimeException(e);
}
while(true){
    try {
        bytes = inputStream.read(buffer);
        String data = new String(buffer,0,bytes);
        //处理数据
    } catch (IOException e) {
        break;
    }
}
try {
    bluetoothSocket.close();
} catch (IOException e) {
    throw new RuntimeException(e);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值