В дополнение к ответу oto, вы также можете использовать Handler / Looper:
import android.os.Handler;
import android.os.Looper;
public class UIActivity extends AppCompatActivity {
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
TextView textView = findViewById(R.id.text_view);
// defines a handler object attached to a UI-thread
handler = new ViewHandler(Looper.getMainLooper(), textView);
ClassA classA = new ClassA(this);
}
public synchronized void handleState(int state, String message) {
Message completeMessage = handler.obtainMessage(state, message);
completeMessage.sendToTarget();
}
}
ViewHandler.kt:
const val MESSAGE_CODE = 0
class ViewHandler(looper: Looper, private val textView: TextView): Handler(looper) {
override fun handleMessage(inputMessage: Message) {
val text: String = inputMessage.obj as String
when (inputMessage.what) {
MESSAGE_CODE -> textView.text = text // update TextView
// update other UI-elements
...
}
}
}
Обновление TextView в ClassA:
public ClassA(UIActivity uiActivity) {
...
// other thread
queue.add(newValue) // invoke every second
String oldValue = queue.remove()
uiActivity.handleState(MESSAGE_CODE, s);
}