以下是一个简单的示例代码,用于扫描并打印所有蓝牙设备的信息:

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = 'MainActivity';
    private static final int REQUEST_ENABLE_BT = 1;
    private static final int REQUEST_PERMISSION_LOCATION = 2;

    private BluetoothAdapter mBluetoothAdapter;
    private TextView mTextView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = findViewById(R.id.text_view);

        // 检查是否支持蓝牙
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
            Toast.makeText(this, '设备不支持蓝牙', Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 获取BluetoothAdapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 检查是否支持蓝牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, '设备不支持蓝牙', Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 请求打开蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        } else {
            // 蓝牙已经打开,开始扫描
            startScanning();
        }
    }

    @SuppressLint('MissingPermission')
    private void startScanning() {
        // 检查是否有定位权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_PERMISSION_LOCATION);
            return;
        }

        // 开始扫描
        mBluetoothAdapter.startDiscovery();
        mTextView.setText('正在扫描...
');

        // 获取已配对的设备
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            mTextView.append('已配对的设备:
');
            for (BluetoothDevice device : pairedDevices) {
                mTextView.append(device.getName() + ' - ' + device.getAddress() + '\n');
            }
        } else {
            mTextView.append('没有已配对的设备。\n');
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                // 蓝牙已经打开,开始扫描
                startScanning();
            } else {
                // 用户拒绝打开蓝牙,关闭应用
                Toast.makeText(this, '需要打开蓝牙才能使用本应用', Toast.LENGTH_SHORT).show();
                finish();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION_LOCATION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授权,开始扫描
                startScanning();
            } else {
                // 用户拒绝授权,关闭应用
                Toast.makeText(this, '需要定位权限才能使用本应用', Toast.LENGTH_SHORT).show();
                finish();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 停止扫描
        mBluetoothAdapter.cancelDiscovery();
    }

    // 发现设备时的回调
    private final BroadcastReceiver mReceiver = 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);
                mTextView.append(device.getName() + ' - ' + device.getAddress() + '\n');
            }
        }
    };
}

需要在 AndroidManifest.xml 中添加以下权限:

<uses-permission android:name='android.permission.BLUETOOTH'/>
<uses-permission android:name='android.permission.BLUETOOTH_ADMIN'/>
<uses-permission android:name='android.permission.ACCESS_FINE_LOCATION'/>

该示例代码会在启动应用时请求打开蓝牙,然后开始扫描附近的蓝牙设备,并打印它们的名称和 MAC 地址。同时,还会列出已配对的设备。当应用关闭时,会停止扫描。

Android 蓝牙扫描示例:如何使用 Bluetooth API 获取所有蓝牙设备信息

原文地址: https://www.cveoy.top/t/topic/ow7u 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录