蓝牙app代码
时间: 2023-07-29 10:12:04 浏览: 45
以下是一个简单的蓝牙APP的代码示例,包含了扫描和连接蓝牙设备的基本功能:
```java
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
// 蓝牙扫描开始
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// 蓝牙扫描结束
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 扫描到蓝牙设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// TODO: 处理蓝牙设备
}
}
};
private final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // SPP蓝牙服务UUID
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// 设备不支持蓝牙
return;
}
if (!bluetoothAdapter.isEnabled()) {
// 蓝牙未开启
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
} else {
// 蓝牙已开启
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(bluetoothReceiver, filter);
}
public void startScan(View view) {
if (bluetoothAdapter.isDiscovering()) {
// 正在扫描中,不重复扫描
return;
}
bluetoothAdapter.startDiscovery();
}
public void connectDevice(View view) {
try {
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMsg(View view) {
try {
outputStream.write("Hello, World!".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(bluetoothReceiver);
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
这是一个简单的蓝牙APP代码示例,其中包含了蓝牙扫描、连接和发送数据的基本操作。具体实现需要根据具体的需求进行调整和完善。