您的位置:首页 > 移动开发 > Android开发

Android6.0蓝牙搜索设备

2017-06-15 23:22 330 查看

BluetoothAdapter

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // null:表示不支持蓝牙
boolean enabled = mBluetoothAdapter.isEnabled(); // true:处于打开状态, false:处于关闭状态


调用系统提示框开启蓝牙

startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 10001);


操作蓝牙别忘了声明权限

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

//Android6.0以后蓝牙搜索 需要定位权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>


开始搜索

//搜索蓝牙需要定位权限
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
mBluetoothAdapter.startDiscovery();//开始搜索


定义广播接收者

Manifest中定义

<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.bluetooth.device.action.FOUND"/>
<action android:name="android.bluetooth.adapter.action.DISCOVERY_FINISHED"/>
</intent-filter>
</receiver>


MyReceiver 继承BroadcastReceiver

public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}

@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);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
Log.e("tag",device.getName() + ":"+ device.getAddress());
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.e("tag","搜索完成");
}
}
}


动态定义/注册

// 设置广播信息过滤
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);//每搜索到一个设备就会发送一个该广播
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//当全部搜索完后发送该广播
filter.setPriority(Integer.MAX_VALUE);//设置优先级
// 注册蓝牙搜索广播接收者,接收并处理搜索结果
this.registerReceiver(receiver, filter);


内部类的方式定义广播接收者

private final BroadcastReceiver receiver = 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);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
Log.e("tag",device.getName() + ":"+ device.getAddress());
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.e("tag","搜索完成");
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息