How to run a function with different parameters parallely in android? - android

I have a function called computeStrokes and I need to call it twice with different parameters.. There is a method in Asynctask called executeOnExecutor which allows a asynctask to run two threads parallely.I was not able to understand how to call this function twice within the doInBackground method of the AsyncTask.
Can Someone just help me with the code of this section i.e doInBackground

If you really need run 2 tasks in parallel from an AsyncTask then you can probably start 2 tasks in doInBackground and wait in there for the completion of both. This can be achieved with the help of Executors and a Future

Related

Android: How to handle multiple tasks

I want to perform multiple tasks in Android. I know I can use AsyncTask for this. But my requirement is I want to execute second task only completion of first task. Then will execute the third task only after completion of second task. How it could be possible.
For this I am thinking to use multiple AsyncTasks i mean inside doInBackground of first AsynTask I want to start second AsyncTask. Similarly inside doInBackground of secondAsynTask I want to start third AsyncTask and so on.... Is it ok if I implement like this with out any performance issue or is there any other way of doing this. Please share your thoughts on this.
Create multiple AsyncTasks and call them in a chain.
E.g.:
Call the first task:
new FirstTask().execute();
Then FirstTask class overrides onPostExecute where it calls the second class:
new SecondTask().execute()
and so on.
If you don't want to reinvent the wheel you could use concat () operator of rxjava.
https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#concat

execute() Call on async task it takes 1 second to call doInBackground() method

I am working on async task. When i call execute() on async task it takes 1 second to call doInBackground() method of async task which I don't want. Does anyone knows how to reduce that time?
Such things are up to the System. Never assume anything about timing when working multithreaded!
Anyways, if your AsyncTask repeatedly does the same work, try using an ExecutorService which gets a Runnable as argument. The ExecutorServices don't destroy the created threads automatically but try to re-use it. That way the starttime might be reduced.
One second to call doInBackground(), or one second to return a result? The reason for using an AsyncTask is to perform longer operations asynchronously from the UI thread. Performing operations that take a while (eg. 1 second) is why they exist.
instead of execute() use executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ...) That way you don't need an ExecutorService.

One difference between handler and AsyncTask in Android

Why can an AsyncTask perform only one job? For example,
task = new SubAsyncTask(...); // assume the parameter is correct.
task.execute(...) //
task.execute(...)// calling once again, it throws exeception.
But a Handler can continously perform more than one task:
hd = new Handler(...); // assume the parameter is correct
hd.sendMessage(...); //
hd.sendMessage(...);// no exeception is thrown.
Is an AasyncTask object for a one-time job only? If I don't want to create multiple object for similar task, should I choose Handler?
Handler and AsyncTasks are way to implement multithreading with UI/Event Thread.
Handler allows to add messages to the thread which creates it and It also enables you to schedule some runnable to execute at some time in future.
Async task enables you to implement MultiThreading without get Hands dirty into threads. Async Task provides some methods which need to be defined to get your code works. in onPreExecute you can define code, which need to be executed before background processing starts. doInBackground have code which needs to be executed in background, in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply. onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread, onPostExecute() method handles results returned by doInBackground method.
So, you dont need to call execute method on AsyncTask multiple TImes, instead you can invoke publishProgress.
Because that is how the class was designed. The idea is: do something with UI (show progress dialog, etc.), do work on background thread and return results, update UI. The Handler is fundamentally different: it lets you post messages, but it does not create a background thread for you. If you don't like how AsyncTask works, build something similar by using threads/executors and handlers.

AsyncTask - How to wait for onPostExecute() to complete before using values it has updated

I have an API in one jar that uses AsyncTask to carry out some work in the background. I need to wait for the result to be returned and then do some more wok with this result.
I signal back to one class in onPostExecute() method and then the result is handled on the UI thread, but the handler needs to be defined as a callback in a different project altogether so I can't just do the work in the onPostExecute.
In the second project I need to wait for the AsyncTask to end AND for the response to be handled, then I need to display the results of the handler to a TextView in an activity in the second project.
Thread.sleep and using a CountDownLatch don't work because the handling is done in the UI thread. Is there any way to do such a thing?
If I understand correctly, you have AsyncTask in one jar and UI that needs to be updated in another jar. If you run them as one application it should not matter where they are located. Since you mentioned that some callback is involved you can just execute this callback in onPostExecute.
The following will be an approximate sequence of events
Activity from jar 2 creates async task and passes callback that knows how to update TextView as parameter to constructor
AsyncTask stores callback in instance variable
Activity executes AsyncTask
AsyncTask in onPostExecute calls method on callback with appropriate parameters
Callback updates TextView

Async task - not clear re called methods

I have a a service class which includes an Async task. In the doInBackground and onPostExecute I call some methods which are in the service class but outside the Async task. When these methods get called will they still be in the thread created by the Async task and therefore not interfering with the main UI.
To illustrate my lack of understanding a bit more should I try to get almost everything that the service class does into the Async task. For example the service starts up as the result of an alarm and in the onStartCommand sets a repeating alarm (this is as Reto Meire's Earthquake example)and creates a database. Would it make sense to move the code for these two operations into the onPreExecute part of the Async task?
No need to do that.. make sure that the method which you want to run in background is called from doInBavkground().. rest you can put in postExecute.... the snippet which you want to run after the backGround task should be in PostExecute(). If You call methods from doInBackground() they still run on background thread.. does't matter where they are.. and if you call it from onPostExecute() then it will run on other thread which ofcourse can make changes in your display.. just like showing dialog etc...
You should always offload as much work as possible to background threads/tasks. Something like database creation should be done in the doInBackground method. The onPreExecute and onPostExecute methods run on the UI thread and are generally used to inform the user of background activity (e.g. using a ProgressDialog).
From experience, I also suggest not using a background service if you can get away with it. If you use one, you should know how to clean it up properly since users generally get annoyed with an application running in the background.

Categories

Resources