蓝牙
蓝牙介绍
是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换。
蓝牙权限
<!-- 用于进行网络定位 -->
<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"/>
打开蓝牙设备
通过隐示意图打开蓝牙并设置允许被扫描以及扫描的时长
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
startActivity(intent);
关闭蓝牙设备
获取蓝牙管理者并调用强制关闭蓝牙的方法
BluetoothManager manager= (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
adapter = manager.getAdapter();
adapter.disable();
搜索附近蓝牙设备
BluetoothManager manager= (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
adapter = manager.getAdapter();
adapter.startDiscovery();
配对蓝牙设备
获取要发送的蓝牙进行配对
ArrayList<BluetoothDevice> blueTooth = new ArrayList<>();
blueTooth.get(position).createBond();
获得所有已经配对的蓝牙设备
BluetoothManager manager= (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
adapter = manager.getAdapter();
adapter.getBondedDevices();
蓝牙连接发送消息
客户端 BlueToothSocket
try {
BluetoothDevice bluetoothDevice = blueTooth2.get(position);
BluetoothSocket socket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);
socket.connect();
String str = "aaaaaaa";
OutputStream outputStream = socket.getOutputStream();
outputStream.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
服务端 BlueToothServerSocket
new Thread(new Runnable() {
@Override
public void run() {
try {
BluetoothServerSocket bluetoothServerSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(adapter.getName(),uuid);
while (true) {
BluetoothSocket socket = bluetoothServerSocket.accept();
new ServerThread(MainActivity.this,socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
try {
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len=inputStream.read(bytes))!=-1) {
final String string = new String(bytes, 0, len);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, ""+string, Toast.LENGTH_SHORT).show();
}
});
}
} catch (IOException e) {
e.printStackTrace();
}