1 回答
TA贡献1826条经验 获得超6个赞
您显然似乎有线程问题。
在您的代码中HomeActivity
,您已经注释掉了允许在手机上打开蓝牙服务器的代码,以便您的 Arduino 设备可以连接到它,并在UUID
RFCOM 模式下提供相关和其他相关参数。
然而,该代码与网络相关并且是阻塞的,因此永远不应该在应用程序UI 线程上执行,该线程负责处理所有 UI 任务,例如显示视图、监视用户交互(触摸事件)等。
这就是您的手机显示白屏且有延迟的原因。
因此,您绝对应该在单独的线程上执行蓝牙逻辑。
我建议使用以下类来处理所有与蓝牙相关的逻辑。这非常简单。
public class BluetoothHandler {
private final Handler handler;
private final BluetoothAdapter bluetoothAdapter;
@Nullable
private BluetoothServerSocket serverSocket;
private BluetoothSocket bluetoothSocket;
public BluetoothHandler(Context context) {
final HandlerThread ht = new HandlerThread("Bluetooth Handler Thread", Thread.NORM_PRIORITY);
ht.start(); // starting thread
this.handler = new Handler(ht.getLooper());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
this.bluetoothAdapter = ((BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
} else {
this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
}
public void startBluetoothServer() {
// execute code in our background worker thread
this.handler.post(new Runnable() {
@Override
public void run() {
try {
serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("name", "your UUID");
bluetoothSocket = serverSocket.accept(); // will wait as long as possible (no timeout) so there is blocking
// do your logic to retrieve in and out put streams to read / write data from / to your Arduino device
} catch (IOException ioe) {
}
}
});
}
@AnyThread
public void writeData(byte[] data) {
// remember, all network operation are to be executed in a background thread
this.handler.post(new Runnable() {
@Override
public void run() {
// write data in output stream
}
});
}
@AnyThread
public void readData(OnDataReadCallback callback) {
// remember, all network operation are to be executed in a background thread
this.handler.post(new Runnable() {
@Override
public void run() {
// read data and notify via callback.
}
});
}
@AnyThread // should be call from your Activity onDestroy() to clear resources and avoid memory leaks.
public void termainte() {
try {
if (serverSocket != null) {
serverSocket.close();
}
if (bluetoothSocket != null) {
bluetoothSocket.close();
}
} catch (IOException ioe) {
}
this.handler.getLooper().quit(); // will no longer be usable. Basically, this class instance is now trash.
}
public interface OnDataReadCallback {
@WorkerThread // watch out if you need to update some view, user your Activity#runOnUiThread method !
void onDataRead(byte[] data);
}
}
添加回答
举报