How to execute some code in Android UI thread async?

DeepNightTwo picture DeepNightTwo · Feb 7, 2012 · Viewed 15.5k times · Source

I'm new to Android development. I've be working on Swing and SWT for several years. Both Swing and SWT has a stratage to execute code in UI thread sync and async. The typical usage is doing some time-consume staff in one thread then display the result in UI thread async.

So my question is, is there similiar stratage in Android? Here is my code. Parameter runnable is some time-consume code. This method will display a waiting dialog during the execution then EXPECT to show a Toast after it is finished. But the Toast need to be show in UI thread. So how to do that?

    public static void showWaitingDialog(final Activity parent, final Runnable runnable, String msg) {

    if (StringUtils.isEmpty(msg)) {
        msg = "processing...";
    }

    final ProgressDialog waitingDialog = ProgressDialog.show(parent, "Please Wait...", msg, true);

    // execute in a new thread instead of UI thread
    ThreadPoolUtil.execute(new Runnable() {

        public void run() {
            try {
                // some time-consume operation
                runnable.run();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                waitingDialog.dismiss();
            }
            // TODO: How to display a Toast message here? execute some code in UI Thread.

        }

    });

}

And is there some words about Android UI system? Such as is it Thread-Safe, how thread works together and so on. Many Thanks!

Answer

prakash picture prakash · Feb 7, 2012

You can use AsyncTask like this.

To call AsyncTask

new getAsynctask().execute("");

and here is the class for geting result.

class getAsynctask extends AsyncTask<String, Long, Integer> {

    protected void onPreExecute() {
        super.onPreExecute();
        loading = ProgressDialog.show(Pass.this, null, "Please wait...");
    }
    protected Integer doInBackground(String... params) {
        try {
            // do your coding
            return null;
        } catch (Exception e) {
            return null;
        }

    }

    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        try {
            if (loading != null && loading.isShowing())
                loading.dismiss();
        } catch (Throwable t) {
            Log.v("this is praki", "loading.dismiss() problem", t);
        }
    }
}