基于Androidstudio的蓝牙通信代码
时间: 2024-05-16 07:12:22 浏览: 170
android 串口收发应用代码
以下是一个基于 Android Studio 的蓝牙通信示例代码:
1. 在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
```
2. 在 layout 文件夹中创建一个布局文件 activity_main.xml:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/button_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search Devices"/>
<ListView
android:id="@+id/list_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button_send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Data"/>
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
```
3. 创建一个 BluetoothAdapter 对象以进行蓝牙通信。在 MainActivity.java 文件中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> devicesArrayAdapter;
private ListView listView;
private EditText editText;
private Button buttonSearch, buttonSend;
private BluetoothDevice device;
private BluetoothSocket socket;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Check if the device supports Bluetooth
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth not supported", Toast.LENGTH_LONG).show();
finish();
return;
}
// Check if Bluetooth is enabled
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, 0);
}
// Initialize UI components
listView = findViewById(R.id.list_devices);
editText = findViewById(R.id.edit_text);
buttonSearch = findViewById(R.id.button_search);
buttonSend = findViewById(R.id.button_send);
devicesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(devicesArrayAdapter);
buttonSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
searchDevices();
}
});
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendData();
}
});
}
// Search for Bluetooth devices
private void searchDevices() {
devicesArrayAdapter.clear();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
devicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
// Start discovery of new devices
bluetoothAdapter.startDiscovery();
registerReceiver(discoveryReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
// Send data to the connected device
private void sendData() {
String data = editText.getText().toString();
try {
OutputStream outputStream = socket.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
Toast.makeText(getApplicationContext(), "Data sent", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error sending data", Toast.LENGTH_LONG).show();
}
}
// Broadcast receiver for discovering new devices
private final BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Connect to the selected device
private void connectToDevice(String deviceAddress) {
device = bluetoothAdapter.getRemoteDevice(deviceAddress);
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
Toast.makeText(getApplicationContext(), "Connected to " + device.getName(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error connecting to device", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(discoveryReceiver);
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
4. 您可以在 MainActivity.java 文件中添加其他方法,例如取消搜索、断开连接等。请注意,此示例代码仅用于演示目的,您需要根据自己的需求进行修改和完善。
阅读全文