0

I often have a situation where I first need to do something in the UI thread (Android in this case), then to some networkstuff in an extra thread, switch back to the UI thread and udate the layout, etc.

This looks most of the time like this:

MainActivity.getActivity().runOnUiThread(new Runnable(){
    @Override
    public void run{
        //Some code here
        new Thread(new Runnable(){
            @Override
            public void run(){
                //Even more code
                MainActivity.runOnUiThread(...);
            }
        }).start();
    }
});

I think this is not optimal in two ways:

  1. It is nested code and not easy enough to read. Yes, it could be simplified through Lambdas, but it would still have many nested parts.

  2. The UI code is all run on one thread, the one provided by the system. For the networking thread, for each part a new thread is started. That's bad for performance.

How can I improve this?

3
  • 2
    If you're worried about the overhead of creating threads, use a thread-pool. But I doubt that this really matters for a typical client application. Jul 14, 2016 at 10:53
  • @CodesInChaos You'd be surprised what some people can do with threads when all it takes to make one is new Thread().start();
    – Ordous
    Jul 14, 2016 at 13:01
  • @Ordous I'd worry far more about those people screwing up thread safety. If not in the trivial locking sense, at least in the sense that by the time the callback is back on the main thread the state isn't what it expects anymore and doing something that doesn't make sense in the new state. Jul 14, 2016 at 13:11

1 Answer 1

2

On android you can use AsyncTask (the equivalent of SwingWorker).

It has 3 methods you can override,

  • doInBackground for the work you want to do in the background thread,
  • onPostExecute called on the UI thread with the return value of doInBackground after it returns, and
  • onProgressUpdate also called on the UI thread in responce to calls to publishProgress.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.