Starting a runnable in background thread
Asked Answered
S

2

18

I have, to my knowledge, implemented a runnable which is created on a new thread. However, the thread does not seem to be running in the background, and the actions taken inside the runnable are stalling the UI with heavy actions.

See below:

custListLoadThread = new Thread(loadRunnable);
custListLoadThread.run();

private Runnable loadRunnable = new Runnable()
{
    @Override
    public void run()
    {
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

        Gen.popup("TEST"); // Creates a toast pop-up.
        // This is to know if this runnable is running on UI thread or not!

        try
        {               
            customers = Db.BasicArrays.getCustomers(CustomApp.Session.businessCode, empId);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    populate();
                    setCustListVisible(true);
                    loading = false;
                }
            });
        }
        catch (final Exception ex)
        {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Gen.popup(ex.getMessage());
                }
            });
        }
    }
};

However this code does not run in the background, it still seems to run on the UI thread. I have placed the line Gen.popup("TEST"); to make sure of this (calling a toast pop up in a non-UI thread should cause an error).

Any ideas as to why this runnable isn't running in the background?

Strickman answered 18/7, 2014 at 11:19 Comment(0)
J
31
custListLoadThread = new Thread(loadRunnable);
custListLoadThread.start();

You need to start the thread, not call the run() method in the current thread.

Judaism answered 18/7, 2014 at 11:23 Comment(1)
That was the problem, thanks very much! Got caught out by the similarities of run and start!Strickman
T
16

If you want to execute code on a background thread that does not do something with the UI:

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //your action
        }
    };
    AsyncTask.execute(runnable);

Of course as written before you can also create a new thread (that is independent from the UI thread):

    new Thread(runnable).start();

In your example you want to update UI elements, so better use a AsyncTask (must be called from UI thread!):

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            // your async action
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            // update the UI (this is executed on UI thread)
            super.onPostExecute(aVoid);
        }
    }.execute();
Twit answered 14/4, 2016 at 6:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.