清单文件中添加:
<!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 蓝牙管理 -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- 蓝牙 -->
<uses-permission android:name="android.permission.BLUETOOTH"/>
判断一下版本号:
//如果版本大于6.0 添加权限
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
//网络定位 和 GPS定位
String[] strings = new String[]{"android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION"};
//添加蓝牙的权限
if(ActivityCompat.checkSelfPermission(this,strings[0])==PackageManager.PERMISSION_GRANTED){
//动态获取权限
requestPermissions(strings,1);
}
}
//蓝牙的管理类
private BluetoothManager bluetoothManager;
//蓝牙的适配器
private BluetoothAdapter bluetoothAdapter;
//蓝牙通讯规范
private UUID uuid = UUID.fromString(“00001106-0000-1000-8000-00805F9B34FB”);
//TODO 本机蓝牙
bluetoothManager= (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
//TODO 获取本机蓝牙(通过蓝牙管理)
bluetoothAdapter=bluetoothManager.getAdapter();
启动蓝牙:
Intent intent = new Intent();
//打开蓝牙
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//允许蓝牙被搜索
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent,1);
关闭蓝牙:
//TODO 关闭蓝牙
bluetoothAdapter.disable();
展示已经配对的蓝牙:
数据源类型为 List<BluetoothDevice>(记得实例化)
适配器(BaseAdapter类型)
//已有的蓝牙设备
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
list.addAll(bondedDevices);
myAdapter_bluetooth.notifyDataSetChanged();
寻找附近的蓝牙:(配合广播一起写)
下文中用到的myRecevier(记得写在子线程中){
//获取Socket
BluetoothServerSocket socket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
//接受连接
while(true){
BluetoothSocket accept = socket.accept();
Log.d("!", "run: 有人连接");
//服务端(另一个类 代码在下面)
new MyServerSocket(accept).start();
}
}
//意图过滤器
IntentFilter intentFilter = new IntentFilter();
//调频 (附近的蓝牙设备)
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
//注册广播
registerReceiver(myRecevier,intentFilter);
//取消注册(在销毁时onDestroy)
unregisterReceiver(myRecevier);
//TODO 0:写广播类 1:注册广播 2:解除注册
class MyRecevier extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//判断频道
if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){//发现一个远程设备
//获得远程设备
//Parcelable:可被打包的
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
list_discovery.add(bluetoothDevice);
myAdapter_discovery.notifyDataSetChanged();
}
}
}
//进行查找
bluetoothAdapter.startDiscovery();
myAdapter_bluetooth_two.notifyDataSetChanged();
在listview 的条目点击事件中写:
//获取当前点击的
BluetoothDevice device = list_two.get(i);
//进行配对
device.createBond();
懒得写了 下期更新