赞
踩
原因:需要配置相关权限,并且位置权限需要进行动态申请
https://developer.android.google.cn/guide/topics/connectivity/bluetooth#SettingUp
<uses-permission android:name="android.permission.INTERNET" />
<!-- 蓝牙权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- google在android6.0之后,为了更好的保护用户的数据安全,所有需要访问硬件唯一标识符的地方都需要申请位置权限 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
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);
}
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());
}
}
}
@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(); // Don't forget to unregister the ACTION_FOUND receiver. unregisterReceiver(receiver); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。