我有一個BLE Android應用程序,我想要接收一個變量已更改的通知,然後更新TextView。 UI組件只能在UI線程上更新,而「OnCharacteristicChanged」方法本質上不是UI線程。所以我做的方式是,如下面我GattCallback(其中BLE_Test是我的主要活動的名稱):Android BLE - 自定義線程是否從GattCallback方法啓動並完成,最終垃圾回收?
@Override
public void onCharacteristicChanged (BluetoothGatt gatt, BluetoothGattCharacteristic characteristic){
//Get the value as a string from the characteristic, as well as the TextView I want to update
Runnable t = new updateViews(viewToUpdate, updateString);
BLE_Test.this.runOnUiThread(t);
}
在那裏我有在主活動這個自定義類:
class updateViews implements Runnable {
TextView viewToChange;
String stringToSet;
public updateViews(TextView viewToChange, String stringToSet) {
this.viewToChange = viewToChange;
this.stringToSet = stringToSet;
}
public void run() {
viewToChange.setText(stringToSet);
}
}
現在,我非常清楚,每次調用「onCharacteristicChanged」時,我都會用新的TextView和String參數創建一個新線程。根據我對Java的瞭解,一旦「onCharacteristicChanged」線程結束,每個「updateViews」線程都應該被垃圾回收。但是「onCharacteristicChanged」在這方面真的是一個正常的線程嗎?我只是想確保這個方法是線程安全的,並且不會導致內存泄漏。另外,如果有更好的方法,讓我知道。謝謝。