前言
我之前做了个人机对战的五子棋, AI算法很垃圾, 然后各种逻辑很糟糕, 已经很久没有维护了, 今天看了篇文章, 是用了蓝牙和Wifi的五子棋对战, 我觉得很有意思, 毕竟自己没做过蓝牙连接这方面的项目, 然后我就把以前做的五子棋搬了出来.
蓝牙基础知识
官方知识:
设置蓝牙、查找局部区域内的配对设备或可用设备、连接设备,以及在设备之间传输数据。
设置权限
权限是一定要设置的,不然根本无法使用,在Manifest设置以下权限:
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
关于6.0以上的蓝牙权限问题
我是基于6.0开发的, 然而我开启了蓝牙却搜索不到其他设备, 感觉很奇怪,搜索了一下,原来:还要添加一个权限(其中一个):
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
设置蓝牙
获取BluetoothAdapter
所有蓝牙Activity都需要BluetoothAdapter,获取这个Adapter很简单, 只需要调用BluetoothAdapter.getDefaultAdapter()这个静态方法即可,它会返回本机的蓝牙适配器.
启用蓝牙可见性
首先检测是否已开启蓝牙可见性, 然后使用
if(!mBluetoothAdapter.isEnabled()) { Intent openIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); openIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500); //设置可见性的时间500s, 0为一直可见 startActivity(openIntent); }
提示:启用可见性就会启动蓝牙.
查找设备
监听广播:
当我们调用BluetoothAdapter.startDiscovery()扫描的时候, 会发出有ACTION_FOUND的广播, 并且Intent还带有EXTRA_DEVICE(包含BluetoothDevice),请看下面代码:
public class BluetoothReceiver extends BroadcastReceiver { private List<BluetoothDevice> mDevices; private List<Bluetooth> mBluetoothList; public OnReceiverListener mOnReceiverListener; public BluetoothReceiver(List<BluetoothDevice> devices, List<Bluetooth> bluetooths, OnReceiverListener onReceiverListener) { mOnReceiverListener = onReceiverListener; mDevices = devices; mBluetoothList = bluetooths; } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { ///获取扫描到的Devi