1 回答

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊
您顯然似乎有線程問題。
在您的代碼中HomeActivity
,您已經(jīng)注釋掉了允許在手機(jī)上打開藍(lán)牙服務(wù)器的代碼,以便您的 Arduino 設(shè)備可以連接到它,并在UUID
RFCOM 模式下提供相關(guān)和其他相關(guān)參數(shù)。
然而,該代碼與網(wǎng)絡(luò)相關(guān)并且是阻塞的,因此永遠(yuǎn)不應(yīng)該在應(yīng)用程序UI 線程上執(zhí)行,該線程負(fù)責(zé)處理所有 UI 任務(wù),例如顯示視圖、監(jiān)視用戶交互(觸摸事件)等。
這就是您的手機(jī)顯示白屏且有延遲的原因。
因此,您絕對應(yīng)該在單獨(dú)的線程上執(zhí)行藍(lán)牙邏輯。
我建議使用以下類來處理所有與藍(lán)牙相關(guān)的邏輯。這非常簡單。
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);
}
}
添加回答
舉報(bào)