Reputation: 25
I have seen all the answers to the previous questions however, can't understand the code to my needs and a bit confused.
I am trying to run two AsyncTasks
simultaneously which are place in two different classes when pressed button in my third class. I understand I need to used executeOnExecutor
but what I can't understand where and what should be the contents to my needs of it. Do I use in both the classes when I'm implementing individually or in the third class where I'm executing when button is pressed.
Code of third class where I'm executing AsyncTask:
new NewAppliance().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new NewChecksAndOperations().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
In both class where these are implemented, I'm targeting HONEYCOMB
too as:
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 11)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Upvotes: 0
Views: 71
Reputation: 5857
In fact, you are already doing it right.
executeOnExecutor() works on a specific AsyncTask instance, hence has to be called for each and every AsyncTask instance for which you want it to take effect.
That is, you can either call:
new MyAsyncTask(..).execute(); // <---- standard
For standard execution, or:
new MyAsyncTask(..).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
For parallel execution.
As I'm sure you already know, default execute() behavior for Android >= 3.0 is sequential processing. Remeber to both instantiate and execute() (or executeOnExecutor()) your AsyncTasks from the UI thread,
Finally, and I understand this is not the subject of your questions, please make a habit of wrapping all of your StrictMode processing within a DEBUG test:
boolean isDebuggable = (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
if (isDebuggable ) {
set StrictMode here..
}
br> You do not want StrictMode tests running at your users...
EDIT
To test a fixed pool executor (instead of an AsyncTask) do as follows:
ExecutorService pool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 2; i++) {
pool.execute(new Runnable() {
public void run() {
// do something with no UI access!
}
});
}
Upvotes: 1