| package org.bd.asynctask; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.widget.TextView; /** * @author Johnny Dew * The Goal of this testing is to check that not only the UI * Thread that can start and execute in each callback of AsyncTask but, * other Worker Thread can start and operates in each callback as well. * * First AsyncTask will be started by UI Thread directly Second * AsyncTask will be started by other Worker Thread. */ public class AndroidAsyncTaskActivity extends Activity { private static final String TAG = "AndroidAsyncTaskActivity"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.v(TAG, String.format("> onCreate # Main Thread ID: %d", Thread .currentThread().getId())); // 1 use UI Thread Log.v(TAG, "> onCreate # Start BdAsyncTask using UI Thread ..."); BdAsyncTask async1 = new BdAsyncTask(); async1.execute(); // 2 use Worker Thread new Thread() { @Override public void run() { SystemClock.sleep(3000); Log.v(TAG, "> run # Start BdAsyncTask using Worker Thread ..."); Log.v(TAG, String.format("> run # Worker Thread ID: %d", Thread .currentThread().getId())); BdAsyncTask async2 = new BdAsyncTask(); async2.execute(); } }.start(); } private class BdAsyncTask extends AsyncTask { private static final String TAG = "BdAsyncTask"; @Override protected void onPreExecute() { Log.d(TAG, String.format("> onPreExecute # Thread ID: %d", Thread .currentThread().getId())); } @Override protected Void doInBackground(Void... params) { Log.d(TAG, String.format("> doInBackground # Thread ID: %d", Thread .currentThread().getId())); publishProgress(params); return null; } @Override protected void onProgressUpdate(Void... progress) { Log.d(TAG, String.format("> onProgressUpdate # Thread ID: %d", Thread.currentThread().getId())); } @Override protected void onPostExecute(Void result) { Log.d(TAG, String.format("> onPostExecute # Thread ID: %d", Thread .currentThread().getId())); } @Override protected void onCancelled() { Log.d(TAG, String.format("> onCancelled # Thread ID: %d", Thread .currentThread().getId())); } } } |