handler.post(runnable) doesnt always execute the run method in android - 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.

Related

Android: Send a signal from a thread in execution

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).

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.

How to time relinquish an Android thread?

I'm in front of a very pretty annoying problem.
I have a code to execute that can take tens of seconds. In final I need to obtain the result of that computation.
If I execute the code merely on the main thread, Android will pop up telling that the thread is blocked and asking if we want to force block.
Well the principle is normal, every OS kernel needs to know our code is still alive and not blocked.
So my question is how to inform Android we are not dead?
For instance the equivalent of a Sleep(0) or ProcessMessage() or anything... but that informs Android that we are not dead, because we are just waiting or performing something pretty long...
Please don't answer me: "let make your computation in a separate thread" since the problem would be exactly the same. The main thread would still need to sit down to know when the thread completes and its result.
You should not run any process that access a database, the internet, or takes longer then .2 seconds on the UI thread.
Asynctask is a very powerful method that allows you to thread computations, while still being able to update the UI at predetermined points. Learn to love it.
As far as letting the user know, make a please wait spinner dialog appear on the pre-execute block, and make it go away on the post execute block.
Edit: To dig into this a bit: The asynctask has three blocks that run on the UI thread onPreExecute, onPostExecute, and onProgressUpdate). In these blocks you can update the UI. Within the doInBackground block, it is its own thread, and so will not block the UI as it processes.
In practice you can set things up to notify that a process is happening in onPreExecute, notify the user of progress during a onProgressUpdate, and then present the final information/clear any please wait dialogs during the onPostExecute block. It was specifically designed to tackle the exact problem you are discussing.
Any process that locks up the system for more then 4 seconds by running on the UI thread will cause a not-responding error to be presented to the user.
http://developer.android.com/reference/android/os/AsyncTask.html
You should compute in another thread and then call back to the UI thread using http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
see http://developer.android.com/guide/components/processes-and-threads.html for more details.
I'll probably catch flack for this but, really, only use AsyncTask where appropriate! (read: quit it!)
Virgil Dobjanschi's answer here:
http://www.youtube.com/watch?v=xHXn3Kg2IQE
.. is really, really good. It is a little more complicated, but it is frequently no more complicated than the actual problem.
While there aren't a lot of details in the original question, it is likely that the best way to solve the problem is (as all answers agree) to use a separate thread. The best way to get to that other thread, though, is likely to be an intent fired at an IntentService. ... and then runOnUiThread, or a Handler, to get the response back.

AsyncTask's doInBackground starts its execution too late after AsyncTask::execute is called

I wrote an AsyncTask and most of the time there is no delay between its constructor been called and its doInBackground been called (0 ms delay).
But whenever contacts syncing is happening at the background, I often experience 1-3 seconds delay between my AsyncTasks's constructor and doInBackground. This delay is unacceptable in my circumstances.
I understand that AsyncTask is a background thread and this problem can be solved by using Thread and setting its priority higher. But what I want to found out is, how do I know what's causing my AsyncTask's doInBackground from being called?
I used adb shell top -m 10 and the process usage seems quite normal when this issue happened.
Any help is appreciated.
thanks
I also face this issue for long period, but now it is solved. Use the code below
new AsyncTaskName().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
instead the code
new AsyncTaskName().execute();
it would solve the problem of running doInbackground late.
We generally don't bother about task scheduling by the jvm. And infact we need not to bother also.
If something needs to be done as quick as possible in your application do it in the constructor itself or use onPre of Asynctask (Remember it execute on UI thread).
But i agree there is something fishy in the doInBackgroud calling in Android AsyncTask
i itself had witnessed the doInbackground didn't get called after onPre. You can google this also. many people had faced it.
I moved to use Traditional Thread.
I wrote my own Asynctask using Traditional thread at core and to mimic onPre and onPost i used Handler. You can go for that option also.
It's important to distinguish between creating and executing the task. (An ASyncTask has a separate execute() method, as well as a constructor, as you have noticed.)
Creating a thread is potentially quite expensive, so you might find that creating the task in advance, and then only executing it at the correct time, gives better results.
If the background operation is likely to be repeated often, you may also find that an IntentService, which handles requests one-at-a-time in a background thread, is more suitable.

AsyncTask does not terminates

I started an AsyncTask. Every seems to be OK and I checked that I get to the end of the task in doInBackground. onPostExecute is called too.
The problem is that I keep seeing in the list of the thread in Eclipse my AsyncTask and if I started again I see a second copy.
Shouldn't the thread be termintated at the end of onPostExecute()?
I have also found this thread about the same problem.
It does not give a definitive answer though.
Thanks
Given that you haven't actually done something wrong, the presence of the Thread doesn't signal that anything is necessarily wrong. The AsyncTask uses an internal thread pool and the threads can be kept around for further future use without the overhead of Thread creation and invocations. So it's entirely possible that everything is just fine.

Categories

Resources