This post show some examples to Get and Set UI elements from AsyncTask. the "Start AsyncTask" button clicked, it new and execute a AsyncTask, to get and set UI elements in various call-back method, in UI thread and background thread.
Starting with HONEYCOMB, AsyncTask are executed on a single thread to avoid common application errors caused by parallel execution - read Run multi AsyncTask at the same time. So call myClientTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) if it is running on device higher than HONEYCOMB.
For the ProgressBar, it's a simple and standard demo: update counter in doInBackground(), and call publishProgress() to call onProgressUpdate() in-directly to update the ProgressBar in UI thread.
In onPreExecute() and onPostExecute(), it run on UI thread, so you can access UI elements directly.
In doInBackground(), it run on background thread; to read data from EditText textIn2 and update TextView textOut2. - In background thread, it can read UI elements, so it can call textIn2.getText() directly. (If I am wrong, please comment) - In background thread, it CANNOT modify UI element, call runOnUiThread() and pass a Runnable to update textOut2 in UI thread.
OnClickListener MyOnClickListener = new OnClickListener(){
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public void onClick(View v) {
MyAsyncTask myAsyncTask = new MyAsyncTask();
/* * Handle multi AsyncTask at the same time * Refer: http://picturedmagazine.blogspot.com/2014/04/run-multi-asynctask-as-same-time.html */ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) myAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else myAsyncTask.execute();
}
};
public class MyAsyncTask extends AsyncTask{
@Override protected void onPreExecute() { //In UI thread, you can access UI here super.onPreExecute(); String s1 = textIn1.getText().toString(); textOut1.setText(s1); }
0 تعليقات