采用普通蓝牙技术,也就是BluetoothSokcet相关API进行数据传输。
思路:首先准备,客户端和服务端。两台手机即可。
蓝牙需要服务端启动accept监听是否有客户端进行相关链接,在这个模式下一个服务端仅仅允许链接一个客户端,一对一。其他客户端进行链接都会报timeout错误。
上代码
第一步,动态申请蓝牙权限
//1.清单文件增加以下权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
//2.代码申请权限
private void applyPermission() {
if (Build.VERSION.SDK_INT >= 23) {
int checkPermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
if (checkPermission != PackageManager.PERMISSION_GRANTED) {
Logger.print("request permission");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isPermission = true;
Toaster.show("已授权");
} else {
isPermission = false;
Toaster.show("拒绝授权");
}
}
第二步,获取蓝牙适配器bluetoothAdapter(客户端服务端都需要,但是服务端不需要扫描)
//获取蓝牙适配器
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
public void searchBluetooth(View view) {
applyPermission();//申请权限
if (bluetoothAdapter == null) {
Toaster.show("不支持蓝牙");
return;
}
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置300内可见
startActivity(discoverableIntent);
}
doDiscovery();//扫描蓝牙 客户端需要
}
//开始扫描
public void doDiscovery() {
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
} else {
bluetoothAdapter.startDiscovery();
}
}
第三步,客户端注册广播接收蓝牙
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);//注册广播信号
registerReceiver(bluetoothReceiver, intentFilter);
private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null && BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Logger.print("名称 : " + device.getName() + "地址 : " + device.getAddress());
if (device != null && device.getName() != null && device.getAddress() != null) {
blueData.add(device);
adapter.notifyDataSetChanged();//适配器刷新list获取已链接的蓝牙列表
}
}
}
};
第四步,启动一个子线程进行链接服务器的socket
ClientThread clientThread = new ClientThread(device);
new Thread(clientThread).start();
class ClientThread extends Thread {
BluetoothDevice device;
public BluetoothSocket socket;
public ClientThread(BluetoothDevice device) {
this.device = device;
}
@Override
public void run() {
super.run();
try {
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
//这里的UUID必须和服务端一致,否则肯定会链接失败
bluetoothAdapter.cancelDiscovery();
socket.connect();
Logger.print("客户端已链接服务端.");
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
//链接成功后,再次启动一个线程不断读取服务器发过来的消息
new ClientInputStream(inputStreamReader,socket).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ClientInputStream extends Thread {
InputStreamReader br;
BluetoothSocket socket;
public boolean isRunning = true;
public ClientInputStream(InputStreamReader br, BluetoothSocket socket) {
this.br = br;
this.socket = socket;
}
@Override
public void run() {
super.run();
while (isRunning) {
try {
char[] data = new char[1024];
int read = br.read(data);
Logger.print("服务端的消息:"+new String(data,0,read));
} catch (IOException e) {
e.printStackTrace();
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
isRunning = false;
}
}
Logger.print("服务器已断开");
}
}
第五步,服务端 服务端其他代码和客户端差不多。线程不一样还有发送消息测试
class ServerThread extends Thread {
BluetoothAdapter adapter;
public BluetoothServerSocket serverSocket;
public BluetoothSocket socket;
public OutputStreamWriter osw;
public ServerThread(BluetoothAdapter adapter) {
this.adapter = adapter;
}
@Override
public void run() {
super.run();
try {
Logger.print("服务端启动");
serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(bluetoothAdapter.getDefaultAdapter().getName()
, UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));//生成服务端socket
socket = serverSocket.accept();//等待客户端链接,这里会进行阻塞。
osw = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
Logger.print("服务端链接成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
第七步,发送消息测试,注意要用子线程进行发送消息
public void sendMsg(View view) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
OutputStreamWriter os = ct.osw;
if(os ==null){
Logger.print("客户端未链接");
return;
}
String msg = "服务端测试信息";
os.write(msg);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}