Android手机支持BLE(蓝牙4.0)通信。笔者遇到了不少问题,供大家分享下。
1、开启蓝牙
BlueAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (!adapter.isEnabled()) {
ToastUtil.showToast("请打开蓝牙服务");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
this.startActivity(intent);
}
else
showDevice();
2、显示附近的蓝牙
这里使用了recyclerView列出所有蓝牙。较为简单,不过要去重
ArrayList<BluetoothDevice> foundDevice = new ArrayList<>();
ArrayList<String> tempDevice = new ArrayList<>();
// 将已配对的设备加入到队列中
foundDevice.addAll(adapter.getBondedDevices());
for (BluetoothDevice device : adapter.getBondedDevices()) {
if (!tempDevice.contains(device.getName() + device.getAddress()))
tempDevice.add(device.getName() + device.getAddress());
}
LogUtil.d("showDevice", "已连接的设备" + tempDevice);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 使用弹出窗。将view加载到弹出窗中
View tempView = LayoutInflater.from(this.getContext()).inflate(R.layout.alert_show_device, null);
recyclerView = (RecyclerView) tempView.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
// 设置recyclerView的适配器。这里较为简单就不贴出代码了。
recyclerView.setAdapter(Adapter);
builder.setView(tempView);
alertDialog = builder.create();
alertDialog.setCancelable(true);
// 监听窗口消失事件。如果窗口消失,则取消蓝牙扫描
builder.setOnCancelListener(new MyCancelListener());
builder.setOnDismissListener(new MyDimissListener());
// 显示弹出窗
alertDialog.show();
// 注册两个广播:发现蓝牙和扫描蓝牙结束
receiver = new BlueToothReceiver();
this.registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND