安卓开发 如何获取可连接的蓝牙设备列表

在stackoverflow上看到这段代码,似乎是可用的
但用我自己手机试验无法显示周围的设备
是有什么权限没有给到吗
mainActivity.java

public class MainActivity extends AppCompatActivity {

ListView listView;

private BluetoothAdapter BA;

private ArrayList<String> mDeviceList = new ArrayList<String>();

private Set<BluetoothDevice> pairedDevices;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

listView=(ListView)findViewById(R.id.devicesList);

BA = BluetoothAdapter.getDefaultAdapter();

BA.startDiscovery();

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

registerReceiver(mReceiver, filter);

}

private final BroadcastReceiver mReceiver = 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);

mDeviceList.add(device.getName() + "\n" + device.getAddress());

Log.i("BT1", device.getName() + "\n" + device.getAddress());

listView.setAdapter(new ArrayAdapter<String>(context,

android.R.layout.simple_list_item_1, mDeviceList));

}

}

};

@Override

protected void onDestroy() {

unregisterReceiver(mReceiver);

super.onDestroy();

}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<ListView

android:id="@+id/devicesList"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:visibility="visible" />

</LinearLayout>

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" />

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

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

<permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" />

<permission android:name="android.permission.BLUETOOTH_ADMIN" />


回答:

有运行时权限的,可使用 https://github.com/getActivit... ,获取蓝牙权限

以上是 安卓开发 如何获取可连接的蓝牙设备列表 的全部内容, 来源链接: utcz.com/p/944223.html

回到顶部