How to execute some code in Android UI thread async?
Asked Answered
M

6

8

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!

Matthia answered 7/2, 2012 at 8:48 Comment(1)
take a look at AsyncTask, it's most supported way developer.android.com/reference/android/os/AsyncTask.htmlUncharitable
G
7

There are several ways for doing that,

  • AsyncTask -

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. Example for using AsyncTask

  • Service -

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Example for Using Service.

  • IntentService -

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. Example for using IntentService.

Gifford answered 7/2, 2012 at 9:1 Comment(0)
B
7

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);
        }
    }
}
Buckra answered 7/2, 2012 at 9:1 Comment(0)
G
7

There are several ways for doing that,

  • AsyncTask -

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. Example for using AsyncTask

  • Service -

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Example for Using Service.

  • IntentService -

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. Example for using IntentService.

Gifford answered 7/2, 2012 at 9:1 Comment(0)
A
2

Whenever you are working with Separate thread which is not your UI thread the best way is to use Handler. Whenever you want to intimate user from your Thread, suppose a progress then send a message to Handler to so. Inside Handler you can handle message and write a code snippet to Change anything on UI. This is the preferred way for Android. see these link1 , link2 & link3

Azelea answered 7/2, 2012 at 8:57 Comment(0)
S
2

You use this AsynTask as a inner class of your activity. In do in background do the time consuming task you want to do and then in on postexecute you can show the text message. call this from your main activity

initTask = new InitTask();
initTask.execute(this);


 protected class InitTask extends AsyncTask<Context, Integer, String> {     
        @Override
        protected String doInBackground(Context... params) {
            // Do the time comsuming task here 
            return "COMPLETE!";
        }

        // -- gets called just before thread begins
        @Override
        protected void onPreExecute() {         
            super.onPreExecute();

        }

        // -- called from the publish progress
        // -- notice that the datatype of the second param gets passed to this
        // method
        @Override
        protected void onProgressUpdate(Integer... values) {

        }

        // -- called if the cancel button is pressed
        @Override
        protected void onCancelled() {
            super.onCancelled();            
        }

        // -- called as soon as doInBackground method completes
        // -- notice that the third param gets passed to this method
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Show the toast message here
        }
    }
Shudder answered 7/2, 2012 at 8:59 Comment(0)
S
2

Use a handler:

static final int SHOW_TOAST = 0;
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();
            }
           handler.sendMessage(handler.obtainMessage(SHOW_TOAST));

        }

    });

}

public Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SHOW_TOAST:
                //Toast here
                break;
        }
    }
};
Shawnna answered 7/2, 2012 at 8:59 Comment(0)
L
1

The Painless threading article from the android developer resources provides different alternatives depending on the specific SDK version.

Lehmann answered 7/2, 2012 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.