How to execute some code in an asynchronous Android UI thread?

I am new to Android development. I have been working on Swing and SWT for several years. Both Swing and SWT have strips for executing code in synchronization of user interface and async threads. A typical use makes it take some time to consume personnel in a single thread, and then displays the result in an asynchronous user interface thread.

So my question is, is there a similar strat in Android? Here is my code. The runnable parameter is some time consuming code. This method displays a wait dialog at runtime, then EXPECT to show Toast after it completes. But Toast needs to be shown in the user interface thread. So how to do this?

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 are there any words about the Android Android interface? For example, this is Thread-Safe, how a thread works together, and so on. Many thanks!

+8
android android-asynctask ui-thread
source share
6 answers

There are several ways to do this,

  • AsyncTask -

AsyncTask allows the user interface thread to be used correctly and easily. This class allows you to perform background operations and publish results to the user interface without the need to manipulate threads and / or handlers. Example for using AsyncTask

  • Service -

A service is an application component that represents either the desire of the application to do longer work while interacting with the user or providing functions for other applications to use. Example for Using Service.

  • IntentService -

IntentService is the base class for services that process asynchronous requests (expressed as intentions) on demand. Clients send requests through startService (Intent) calls; the service starts as needed, processes each intention, in turn, using the workflow and stops when work is completed. Example for using IntentService.

+7
source share

You can use AsyncTask like this.

Call AsyncTask

new getAsynctask().execute("");

and here is the class to get the 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); } } } 
+7
source share

Whenever you work with a separate thread that is not your UI thread, the best way is to use Handler. Whenever you want to intimately associate a user with your thread, assume progress, then send a message to the handler. Inside the handler, you can process the message and write a piece of code to change something in the user interface. This is the preferred option for Android. see these link1 , link2 and link3

+2
source share

You use this AsynTask as an inner class of your activity. In the background, perform the time-consuming task that you want to perform, and then in a post-excursive state, you can display a text message. name it 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 } } 
+2
source share

Use 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; } } }; 
+2
source share

The stainless steel product from Android Developer Resources provides various alternatives depending on the specific version of the SDK.

+1
source share

All Articles