Android: Send a signal from a thread in execution - android

Situation: I make a call to a thread, which in turn pings a server with a serialized object. Immediately after that, a function call pings the server with some parameters.
Problem : The thread indeed get called before the function, but the function finishes execution before the thread does. Result is that the parameters are sent before the serialized object.
How do I make the function not start its execution, until the thread has finished ? In other words, can the thread send a "signal" that its finished, so that I can begin execution of the remainder of the code ?

I think this is a book example of a situation where CountDownLatch should be used. Indeed, if you go to the documentation page you'll find a example of what you seem to need (I mean the CountDownLatch(1) example).

Related

Waiting for a server task to complete

I have a situation where I have to do a server call from Android and based on the result of the call ( result would be either true or false) I want to proceed ahead in the code flow and pop a Dialog based on this result. Till the call is complete I don’t wish to proceed ahead in the code flow or logic. In short, I want to carry out a sync operation
At the server side, I will receive a HTTP Post request from android client and based on the parameters in the POST I do some processing by fetching values from the DB and return back true or false to android client.
To carry this out correctly on Android side, I researched and got two options.
Using Handler with AsyncTask does not work in my case because if
I use AsyncTask with Handler, the task result will arrive
sometime in future in Handler and the calling function will return
immediately whereas I want the calling function invoking
AsyncTask to finish i.e. wait till the server returns backs before I
proceed ahead .
The other option that I came across was to use
AsyncTask get() method . Since I am not carrying out a long running
task and rather performing a simple calculation on serverside, this
may not cause a an ANR situation even if I block the UI thread.
Are there any better options of carrying this out ? Is AsyncTask get() here actually one of the correct uses of get() ?

Android AsyncTask get() form another AsyncTask()

Background
I have an AsyncTask (call it uploadHeader) that uploads some data to a server.
I have a second AsyncTask (uploadDetail) that uploads some related data, which requires the initial data to have been uploaded: the header upload returns an id issued by the server, which is used to update the local detail records, before they're uploaded.
If at the time uploadHeader was initially called there were connectivity issues, the header info won't have been uploaded.
So at the start of uploadDetail.doInBackground() I check the status of the local header record to see if it has already been successfully uploaded to the server, and if not, call an uploadHeader.get() to upload the header and wait to get the id back, before I upload the detail records.
Problem
It just seems to hang at the get() call. Debugging it, it seems to be creating a FutureTask and then looping somewhere inside that. It looks as if the second AsyncTask is being queued to run after the first one finishes, which it never does since it's waiting on the second.
I've read a number of other posts/articles on calling one AsyncTask from another, but they all seem to be focused on getting the two to run in parallel. I want this to block, until the other task finishes. It's also been mentioned that "execute(Params...) must be invoked on the UI thread.", none of the articles mention get(). Or is get() basically identical to execute() apart for waiting for the result?
As a workaround, I could put the http call to upload the header in a separate class and call that from both uploadHeader and uploadDetail, so uploadDetail wouldn't need to create an uploadHeader task.
I'd just like to understand why it's not working as it is.
get() will block your execution until the second AsyncTask returns a value, don't do this if your first AsyncTask is doing some work that repercutes on the user interface of even in the workflow you've designed.
I'd definitely use Handlers on both AsyncTasks to communicate between them, even another one for the UI if you need to. You may find a good example here. For reference, look here.

AsyncTask oddity

I'm working on the live frames that I get from the android camera. I don't treat all the frames but when I do, I create a Thread so as to keep the ui thread responsive. The thing is, that within this new thread at some point I want to update a server so I start an Asynctask.
According to the documentation, Asynctasks should be started by the UI thread. So I use runOnUiThread to start them. In accord with the documentation, what happens is that if I change the activity or change configuration, the activity is restarted, my task dies and I never get the server's response(which is saved in a database table). I'm curious, so I tried starting the Asynctasks from the worker thread, and lo! I get the server response even if the activity has changed. What is interesting is that if my UI thread is number 1 and my worker thread is number 2, the server's response treatment happens on 1 and not 2. I can more or less understand this because thread 2 has finished so the asynctask probably falls back onto thread 1, but I really don't get why this thread is still running if I'm in an other activity? does anyone know what's happening?
I'm aware that even if this effect may seem very useful, it isn't a good idea to use it. But I'm just curious about why it works this way.
When configuration change (generally speaking), the activity is recreated. At that moment, you have 2 instances of Activity. The old one pending collection and the new one. Say that the old one had a worker thread W. W is pending collection. However, it is very possible that it is able to continue its work before it is collected. (If you create a thread with an infinite while loop, you can notice that it will stop but eventually.)
When you start the AsyncTask from the UI thread, results will be posted to the UI Thread (delivered in onPostExecute). When the activity is pending garbage collection, the onPostExecute will not be post to the ui thread that is DONE.
However, when you started the AsyncTask from the worker thread, results will be posted as long as the calling thread (your W thread) is there. "Is there" was described in the first paragraph of the answer.

handler.post(runnable) doesnt always execute the run method in android

I have created a Handler instance in the main ui thread(mUIHandler) and from a worker thread(other thread) when i am trying to execute the run method of the runnable the run method gets executed almost 9 out of 10 times but there is that 1 time when it doesn't get executed.
mUIHandler.post(uiRunnable) --> does it not always guarantee to execute the run method present in the runnable?
I even added log methods to check and could see that the logs till the post method innvocation gets executed but the run method logs don't get displayed.
How does the post(runnable) work internally? does it guarantee that the ui thread(thread with the handler) will excute this as soon as post is invoked?
Any help would be appreciated.
Thanks!
I've run into this problem as well on Android 2.2, in my case both Runnables and Messages were being used with the same Handler.
After looking at the Handler source code, it turns out that removing messages with a 'what' value of 0 also removes all queued Runnables. This happens because in the Handler class a Runnable is internally posted as a message with a 'what' value of zero, which are all removed by any call to removeMessages(0). Therefore, avoid using zero as message id.
I have never seen a Handler not properly run the posted runnable. Some things to investigate:
Is there any logic that might result in a race condition between data the thread could be potentially interacting with while the UI-thread runnable is executing?
Do you have a try/catch anywhere that might be silently eating an exception?
My vote (without having seen your code) is that it's probably #1. You wouldn't be the first person to fall victim to hard-to-track-down race conditions as a result of concurrent logic.

Android Asynk Task

is a good practice to have an Asynk task with a loop like this inside?
while (true) {
check queue and request API
Because i need to wait for my Activities and service needs to comunicate with the APi.
Thanks
I am assuming the "queue" is a Java queue, perhaps a LinkedBlockingQueue. If so, that queue is unnecessary, as AsyncTask has a queue to go along with its thread pool.
So, the question is: what triggers things to go in the queue?
If the trigger is a user event (e.g., menu choice, button push), just have it launch an AsyncTask, or have it have a Service launch an AsyncTask. That work will be queued up by the AsyncTask system.
If the trigger is the passage of time (e.g., we want to check an external server every 10 minutes), I would use AlarmManager and consider switching from AsyncTask and a Service to using an IntentService.
I have a priority queue in order to select first the important calls to the API.
My program have two services:
One calls the API when a message is added to the queue. The call to the api is made by an Asinc Task in this way:
messages.add(request);
new DownloadApiTask().execute();
The other service is updating the local database. For that, i have a loop in which i call the first service in order to get data from the API. The basic structure is:
while ihave data to updload
mFirstService.putMessage(request).
Fine, the problem is i have a rejected Execution Exception every X calls, I think it can be because i invoke the asinc task every time i take a message.
For that, i was thinking in force to the asinck task to check the queue instead executing it.
I hope you can understand my problem.
Thanks

Categories

Resources