在Android中检测蓝牙Le设备 [英] detect bluetooth Le devices in Android

查看:139
本文介绍了在Android中检测蓝牙Le设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android应用程序开发的初学者.我已经尝试阅读文档,但是却一无所获(Android教程中的功能,例如StartLeScan()已被弃用,等等...)

I'm a beginner in android app development. I've tried reading the documentation but am getting nowhere (functions in Android's tutorial such as StartLeScan() have been deprecated, etc...)

是否有一个简单的函数返回蓝牙设备列表?

Is there a simple function that returns a list of bluetooth devices ?

类似于getDevices()->(设备列表)的东西?

something like getDevices() -> (list of devices) ?

谢谢

推荐答案

基本上,这取决于您要定位的Android版本.因为api改变了棒棒糖(21).

basically it depends on which android version you are targeting. since the api has changed a bit in lollipop (21).

在您的活动中,获取蓝牙适配器

in your activity, get the bluetooth adapter

BluetoothManager bm = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE)
BluetoothAdapter mBluetoothAdapter = bm.getAdapter();

// Ensures Bluetooth is available on the device and it is enabled. If not, 
// displays a dialog requesting user permission to enable Bluetooth. 
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { 
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

然后您应该检查您要定位的Android版本

then you should check which android version you are targeting

int apiVersion = android.os.Build.VERSION.SDK_INT;
if (apiVersion > android.os.Build.VERSION_CODES.KITKAT){
 BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
 // scan for devices
 scanner.startScan(new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            // get the discovered device as you wish
            // this will trigger each time a new device is found

            BluetoothDevice device = result.getDevice();
        }
    });
} else {
    // targetting kitkat or bellow
    mBluetoothAdapter.startLeScan(new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            // get the discovered device as you wish

        }
    });

// rest of your code that will run **before** callback is triggered since it's asynchronous

别忘了在清单中添加权限

dont forget to add permissions in your manifest

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

这篇关于在Android中检测蓝牙Le设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆