Android:使用BLE蓝牙

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值