蓝牙连接手机,并在手机上对数据进行显示的代码实现
时间: 2024-03-11 18:47:07 浏览: 254
以下是一个简单的Android Studio代码示例,可连接到Arduino蓝牙模块并显示来自称重传感器的数据:
MainActivity.java:
```java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket mBluetoothSocket = null;
private InputStream mInputStream = null;
private Thread mWorkerThread = null;
private byte[] mReadBuffer;
private int mReadBufferPosition;
private TextView mTextView;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // 蓝牙串口通信UUID
private static final String DEVICE_ADDRESS = "00:00:00:00:00:00"; // 你的Arduino蓝牙模块的MAC地址
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.text_view);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(this, "Please enable your Bluetooth and re-run this program", Toast.LENGTH_LONG).show();
finish();
return;
}
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(DEVICE_ADDRESS);
try {
mBluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
mBluetoothSocket.connect();
mInputStream = mBluetoothSocket.getInputStream();
beginListenForData();
} catch (IOException e) {
Toast.makeText(this, "Error connecting to device", Toast.LENGTH_LONG).show();
finish();
return;
}
}
private void beginListenForData() {
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
String weight = (String)msg.obj;
mTextView.setText("Weight: " + weight + " g");
}
};
mWorkerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
int bytesAvailable = mInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == '\n') {
byte[] encodedBytes = new byte[mReadBufferPosition];
System.arraycopy(mReadBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
mReadBufferPosition = 0;
handler.obtainMessage(1, data).sendToTarget();
} else {
mReadBuffer[mReadBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
Thread.currentThread().interrupt();
}
}
}
});
mReadBuffer = new byte[1024];
mReadBufferPosition = 0;
mWorkerThread.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mWorkerThread != null) {
mWorkerThread.interrupt();
}
try {
mInputStream.close();
mBluetoothSocket.close();
} catch (IOException e) {
// ignore
}
}
}
```
在这个示例中,我们首先检查设备是否支持蓝牙,并确保它已启用。然后,我们使用`BluetoothAdapter`对象获取到Arduino蓝牙模块的`BluetoothDevice`对象,并使用该对象创建一个`BluetoothSocket`对象。接下来,我们使用该`BluetoothSocket`对象获取输入流,并在`beginListenForData()`方法中启动一个新的线程来读取数据。在该方法中,我们使用一个`Handler`对象将读取到的数据发送到UI线程,以便在`TextView`控件中显示它。最后,在`onDestroy()`方法中,我们关闭蓝牙连接和线程,以便释放资源。
请注意,此示例仅仅是一个基础示例,实际应用中还需要进行更多的错误处理和异常处理。
阅读全文