Android Threads with infinite loops and UI

1.6k Views Asked by At

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?

2

There are 2 best solutions below

0
On

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.

0
On

Android has only one ui dispatcher thread for ui operations and safe mechanism for thats (throwing exception if operation is not performed in ui thread). So, if you want to update ui, you have to do it in dispatcher thread. You can use for this handler, or you can use easy Activity.runOnUiThread. so, in you code, just

class BtConnection implements Runnable {

    @Override
    public void run() {
        NXTConnector conn = new NXTConnector();
        dos = new DataOutputStream(conn.getOutputStream());
        dis = new DataInputStream(conn.getInputStream());

        while(true){
            runOnUiThread(new Runnable(){
              run(){
                 int nextPageIndex = dis.readInt();
                webView.loadUrl(indexToUrl(nextPageIndex));
              });
        }
    }
 }

and, if you need really quick update on screen, then you can use SurfaceView. SurfaceView has not bounded to ui thread. so, you can do whatever you want in this object. but, it is simple a draw object. so, you can only draw some geometric shapes on this object.