Harri Smått schrieb:
That's not true. Android supports basic Java Threads and there's no
reason for not to use them when appropriate. But the thing is, you can
not alter UI components outside of UI Thread. In your case it would be
updating the textual contents of TextView. See method named
runOnUiThread , it gives easy access for executing UI code from Threads.

Thanks, I guess runOnUiThread() corresponds to the
SwingUtilities invokeLater(), plus some smarts to bypass
posting if already in UiThread (*).

I guess there are situations where the smarts is not needed
and where one wants a invokeAndWait(). I built myself
AndroidUtilties which provide the later. The code reads
as follows:

public class AndroidUtilities {

    public static void invokeLater(View v, Runnable r) {
        if (!v.post(r))
            throw new RuntimeException("looper missing");
    }

    public static void invokeAndWait(View v, Runnable r)
        throws InterruptedException {
        WaitAdapter wa = new WaitAdapter(r);
        AndroidUtilities.invokeLater(v, wa);
        wa.doneJob();
    }

}

class WaitAdapter implements Runnable {
    private Runnable job;
    private volatile boolean donejob;
    private final Object donelock = new Object();

    WaitAdapter(Runnable j) {
        job = j;
    }

    public void run() {
        job.run();
        synchronized (donelock) {
            donejob = true;
            donelock.notifyAll();
        }
    }

    void doneJob() throws InterruptedException {
        synchronized (donelock) {
            while (!donejob)
                donelock.wait();
        }
    }

}

The annoying thing is that one has to remember and/or
pass around a view all the time. The above code could
of course also be adapted so that it takes an activity
parameter instead of a view parameter, but still the
annoyance will be there.

Bye

(*)
http://stackoverflow.com/a/9350672/502187




--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to