I am fairly new to Android and I didn't get the Android threading idea yet.
Here I have BtConnection
class which communicates with Lego NXT via Bluetooth. I want to change my webView
according to message from NXT. I want to change webView
as soon as I get any message. Like this
class BtConnection implements Runnable {
@Override
public void run() {
NXTConnector conn = new NXTConnector();
dos = new DataOutputStream(conn.getOutputStream());
dis = new DataInputStream(conn.getInputStream());
while(true){
int nextPageIndex = dis.readInt();
webView.loadUrl(indexToUrl(nextPageIndex));
}
}
}
And then...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("file:///android_asset/html/index.html");
new Thread(new BtConnection()).start();
}
But this is wrong, because new Thread(new BtConnection())
can't touch UI.
What should I do?
The solution here , is to use Handler between the UI thread and your others threads :
https://developer.android.com/training/multiple-threads/communicate-ui.html
What you have to do is to define a handler on the UI Thread which gonna handle the incoming message from other threads.