J'ai une application Android BLE où je veux recevoir une notification qu'une variable a changé, puis mettre à jour un TextView. Les composants de l'interface utilisateur ne peuvent être mis à jour que sur un thread d'interface utilisateur et la méthode "OnCharacteristicChanged" n'est pas intrinsèquement un thread d'interface utilisateur. Donc, la façon dont je le fais est comme ci-dessous dans mon GattCallback (où BLE_Test est le nom de mon activité principale):Android BLE - Les threads personnalisés sont-ils démarrés et finis à partir des méthodes GattCallback, puis récupérés par le garbage?
@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);
}
Là où j'ai cette classe personnalisée dans l'activité principale:
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);
}
}
maintenant , Je suis très conscient qu'avec chaque appel à "onCharacteristicChanged", je crée un nouveau thread avec de nouveaux paramètres TextView et String. De ma connaissance de Java, chaque thread "updateViews" doit être récupéré après le thread "onCharacteristicChanged". Mais "onCharacteristicChanged" est-il vraiment un fil normal à cet égard? Je veux juste m'assurer que cette méthode est sûre de thread et n'entraînera pas des fuites de mémoire. Aussi, s'il y a une meilleure façon de le faire, faites le moi savoir. Merci.