原因:需要配置相关权限,并且位置权限需要进行动态申请
Android官方蓝牙指南
https://developer.android.google.cn/guide/topics/connectivity/bluetooth#SettingUp
配置权限:AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<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" />
在代码中动态申请位置权限:MainActivity.java
ps:关于动态申请权限的成功/失败处理自行百度
if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
}
广播类:BluetoothBroadcastReceiver.java
public class BluetoothBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "BluetoothBroadcastRecei";
@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);
Log.e(TAG, "设备名字:" + device.getName() + "\n设备地址:" + device.getAddress());
}
}
}
检测及开启蓝牙功能:MainActivity.java
@Override
protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
|| (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
receiver = new BluetoothBroadcastReceiver();
registerReceiver(receiver, filter);
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter!=null){
if(bluetoothAdapter.isEnabled()){
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
else {
bluetoothAdapter.startDiscovery();
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
|