Android通过蓝牙与PC通信
在编程模型上,这里把电脑设计成服务器端,用Java实现一个Windows电脑上的蓝牙服务器,名为:PCBluetoothServer
。
Java SE
本身并没有实现蓝牙功能模块,如果在Windows通过Java实现蓝牙功能,需要额外的导入两个jar(64位):
<dependencies>
<!-- https://mvnrepository.com/ -->
<dependency>
<groupId>io.ultreia</groupId>
<artifactId>bluecove</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
部署在Windows PC电脑上的蓝牙服务器端代码PCBluetoothServer.java
服务端接收到客户端信息后,会主动给客户端回复信息
public class PCBluetoothServer {
private String UUID = "0000110100001000800000805F9B34FB";
public static void main(String[] args) {
new PCBluetoothServer();
}
public PCBluetoothServer() {
try {
/**
* 开启一个连接,等待访问
*/
String url = "btspp://localhost:" + UUID;
StreamConnectionNotifier notifier = (StreamConnectionNotifier) Connector
.open(url);
serverLoop(notifier);
} catch (Exception e) {
e.printStackTrace();
}
}
private void serverLoop(StreamConnectionNotifier notifier) {
try {
// infinite loop to accept connections.
while (true) {
System.out.println("等待连接");
/**
* 阻塞方法acceptAndOpen(),一直等待
*/
handleConnection(notifier.acceptAndOpen());
}
} catch (Exception e) {
System.out.println(e);
}
}
/**
* 处理连接请求,使用线程异步处理,避免一直等待处理完成
* 先要接收到客户端信息,才可以继续执行
* @param conn
* @throws IOException
*/
private void handleConnection(StreamConnection conn) throws IOException {
new Thread(new Runnable() {
@Override
public void run() {
try {
OutputStream out = conn.openOutputStream();
InputStream in = conn.openInputStream();
DataOutputStream dos = new DataOutputStream(out);
DataInputStream dis = new DataInputStream(in);
// 阻塞方法
String read = dis.readUTF();
System.out.println("接收到Client:" + read);
//给客户端回复信息
dos.writeUTF("Server receive you Msg,Thank you!");
dos.close();
dis.close();
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
Android客户端
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
/**
* Android手机客户端通过蓝牙发送数据到部署在Windows PC电脑上。
* 如果运行失败,请打开手机的设置,检查是否赋予该App权限:
*
* <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
* <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
*
* <uses-permission android:name="android.permission.BLUETOOTH" />
* <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
*
* Android手机的蓝牙客户端。
* 代码启动后检查当前手机是否已经和蓝牙名称为 TARGET_DEVICE_NAME 的配对成功。
* 本程序为测试程序,需要先手动使蓝牙与PC进行配对
* TARGET_DEVICE_NAME 为PC端配对的蓝牙设备名
* MY_UUID 与PC端应该保持一致
*
*/
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
private BluetoothServerSocket serverSocket;
//要连接的目标蓝牙设备。
private final String TARGET_DEVICE_NAME = "DELL-PC";
private final String TAG = "蓝牙调试";
private final String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";
/**
* @param
* @return
* @description 获得和当前Android已经配对的蓝牙设备
* @date: 2020/4/5 10:05
* @author: lxf
*/
private BluetoothDevice getPairedDevices() {
// 获得和当前Android已经配对的蓝牙设备。
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice pairedDevice : pairedDevices) {
// 把已经取得配对的蓝牙设备名字和地址打印出来。
Log.d(TAG, pairedDevice.getName() + " : " + pairedDevice.getAddress());
if (TextUtils.equals(TARGET_DEVICE_NAME, pairedDevice.getName())) {
Log.d(TAG, "已配对目标设备 -> " + TARGET_DEVICE_NAME);
return pairedDevice;
}
}
return null;
}
/**
* 开启蓝牙
*/
private void openBluetooth() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = getPairedDevices();
if (device == null) {
// 注册广播接收器。
// 接收蓝牙发现讯息。
// IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
// registerReceiver(mBroadcastReceiver, filter);
// if (mBluetoothAdapter.startDiscovery()) {
// Log.d(TAG, "启动蓝牙扫描设备...");
// }
} else {
try {
connectService(device, MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void connectService(BluetoothDevice device, String uuid) throws IOException {
try (BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString(uuid));) {
Log.d(TAG, "连接服务端...");
socket.connect();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
/**
* 阻塞方法
*/
dos.writeUTF("hello server, I am client");
dos.flush();
DataInputStream dis = new DataInputStream(socket.getInputStream());
/**
* 阻塞方法
*/
String readUTF = dis.readUTF();
System.out.println("接收到服务端信息:" + readUTF);
TextView textView = findViewById(R.id.textView);
textView.setText(readUTF);
textView.setTextColor(Color.RED);
dos.close();
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button myBtn = findViewById(R.id.myBtn);
myBtn.setOnClickListener(v -> {
Toast.makeText(MainActivity.this, "开启蓝牙", Toast.LENGTH_SHORT).show();
openBluetooth();
});
}
}
客户端运行结果
服务端运行结果