how to update view in UI thread from worker thread - android-webview

I have two threads running one id UI and other is worker thread. Worker thread continuously reads on port for some data from server, when appears I need to update my webview in UI thread. Worker thread again continues to read and never ends. Plz suggest how to accomplish this??
it may be likely as 'signals in C++' which causes a method in called thread to be invoked..!!
I tried: 1)As running worker thread on UI (runOnUIThread)may degrade UI webview performance, and if I put the thread on sleep it may miss data appeared at port when sleeping..(i m not sure!)
2)using Handler, I hav to specify time before calling thread again n again which may cause to miss data if appeared on port as like sleep().
3)Having a separate thread in same class,it gives: any other thread cant update view of main UI thread.
Plz help.. :(

Maybe I am missing something, but it seems like creating a Handler object and then using the post() method is what you need: http://developer.android.com/reference/android/os/Handler.html#post%28java.lang.Runnable%29

I had a similar problem. I have a UI thread and a few threads that do backend serverices. I use the observer Pattern to have the services update the UI and to do so I have the update method in a new thread and call runOnUiThread() to have it update the UI. It seems to work well for something quick. If you want something better than a quick band-aid I would suggest reading this android threading guide from Google and trying to incorporate it with your design.

Related

How can one thread determine if a different thread has crashed?

I have a background thread that is doing a bunch of work - loading the application. The main thread is displaying progress on a UIProgressView.
The background thread is being spawned with performSelectorInBackground (though, I'm not wed to this method if a different approach makes this problem easier to solve)
[self performSelectorInBackground:#selector(loadAppInBackground) withObject:self];
On a couple occasions a bug has caused the background thread to crash (different bugs as the app evolves) which results in the progress bar stopping, but the user getting no clear indication that anything is wrong.
I'd like to detect this situation and fail more gracefully than simply hanging until the user gives up on waiting.
Because the duration of the load process can vary greatly, simply timing out isn't an ideal option.
What's the best way for the foreground thread to detect that the background thread has failed? Since the foreground thread is busy dealing with the UI, would it require a second background thread to monitor the first? That seems ugly.
Is there some thread-to-thread communication mechanism that could be used to "ping" the background process? Better yet, a low level system mechanism of checking the status of other threads?
The debugger knows about all the threads that are running... and seems to know their status. I'm wondering if there's a call available to my app to do the same.
If the background task runs in some sort of regular cycle (eg, there's a big loop where much of the work gets done), it can set a flag every so often to indicate that it's still alive.
One way to do this is to have background thread store [NSDate timeIntervalSinceReferenceDate] somewhere, and, in your main thread, occasionally (perhaps on a timer) compare that to the current time. If the difference is greater than some reasonable limit you can guess that the background thread has died.
Another way is to have the background thread simply set a Boolean, and have the main thread interrogate that and clear it on some regular basis. If the Boolean doesn't get set again between main thread interrogations you can infer that it has died.
The first technique has the advantage that you can "tune" the "reasonable limit" to tolerate code (in either thread) that is somewhat irregular in it's timing. The second approach generally requires timings that are more predictable.
Of course with either approach you want to somehow avoid "blowing the whistle" if the background thread has just finished up and you simply haven't recognized that yet.
A common technique is to have an extra thread to check for life signs of the thread in question - a so called heartbeat thread. The heartbeat thread polls the thread by checking if it responds in a timely manner, if not, deems the thread dead and terminates it.
A simple heartbeat thread implementation would be to check a counter that is incremented regularly by the other thread, if the counter is not incremented within a certain time it is regarded as dead and then an appropriate action could be taken like restarting thread or killing app. Another more common way is if the hb thread sends messages to the thread and checks for a response with a timeout.
It seems like there is no mechanism in objective c to check the status of a background thread directly. Any of the answers provided are decent options... either timing out, or having the thread create some sort of evidence of its continued existence.
I was hoping for something a little more simple, reliable, and real-time.
I'm going to experiment with catching an exception in the thread and perhaps producing a notification like "BackgroundThreadException" that the foreground thread could listen for and react to.

Do I have an option to access all threads running in my app?

I have used detachNewThreadSelector method to create threads in my app. At some point of time, when user is logged out from the app, I should kill all running threads in the app. How can I achieve it?
If you create a thread with detachNewThreadSelector you pretty much have to let it finish by itself :(
A better option if you want to be able to control background tasks would be NSOperationQueue - with this you can pass cancel messages to operations.
(Apple docs here)
EDIT : If you don't want to use NSNotificationCenter, you could set a flag that your background threads periodically check and if it's set they will exit themselves. However, you would have to be careful about thread safety there :)
Use "normal" NSThread constructor - (id)initWithTarget:... and save your thread object.
Or save thread objects somewhere after thread start.
Don't save thread objects at all, just use some separate flags that you'll check in your threads and exit them.

Abort button in ZK

I want to put an Abort Label or button below...the processing message is shown in ZK. or is there any way to load my custom components instead of the default Processing. message in ZK.
Want will happen if do abort while processing is it ideal to do that, I want to do that anyways as few times my application sleeps while loading
ZK is built on Servlets. When the busy button is shown on the ui awaiting the ajax response then the servlet thread is doing long running work on the server. Perhaps it would be possible to send another thread to interrupt the first thread but really that is high risk as all the servlet threads can end up doing long running work and no new ones will be available to cancel them.
The best solution is that long running work should not be on the servlet thread but handed off to a background thread or message queue. See zk-asynchronous-ui-updates-and-background-processing. In that example the work is offloaded to a java.util.concurrent.ExecutorService which has an API to cancel the work.
Note that cancelling of a working thread uses interruption and it is not guaranteed that code which doing the work will respond to the interrupt properly such that it is actually cancellable. The answers on the thread cancel with executor service outline some of the issues and you should test whether the work you are doing can be interrupted using the API.

Killing a thread or an alternative

Is there any way I can kill a thread spawn through:
[NSThread detachNewThreadSelector:#selector(serverFetchInThread) toTarget:self withObject:nil];
The scenario I am working on is that in my main thread I am letting user enter data in my search bar and what ever user is typing I need to send to server for searching in a separate thread. Now, if user changes his selection by deleting old data and entering new data I do not want the previous thread to waste its time, kill it and spawn a new thread with new data.
Be there any other better way to handle this situation, please guide me.
No, there is no way to kill a thread from another thread. And for good reason as there is no way to do so in a fashion where the targeted thread is killed without risk of crashing the app.
To directly answer your question; you need to have some kind of a flag that indicates to the thread that it should stop doing whatever it is doing and exit.
However, a couple of questions are raised by your question:
First, why are you using threads and not using GCD? Concurrency via GCD or NSOperation is the generally recommended way to solve such problems.
Secondly, if you are talking to a server, are you using HTTP (most of the time, that is the case)? If so, why not directly use the asynchronous features of NSURL and friends?
Have a good look at using NSOperationQueue.
You can subclass NSOperation it to wrap up your server communications, and even make that queue serial (maximum operations = 1).
If a server operation is not yet finished and user has generated more input, you can cancel the existing one, and add the new one.
Due to the effect of the NSOperation wrapping your connection, you can just use the simple synchronous version and keep the connection handling very straightforward.
Also worth mentioning is compatibility. I would prefer to use GCD and blocks, but for compatibility, NSOperationQueue is required.

Avoid main thread freezes when UIWebView tries to blockingly lock the web thread

All UIWebViews share a single web thread.
When one of them is init-ed, removed from superview etc., they will attempt to lock the web thread from the main thread in a blocking fashion, thus temporarily freezing the run loop of the main thread.
If the web thread is busy, e.g. while doing a long synchronous XMLHttpRequest, this may block the main thread for a long time.
Is there a way to avoid this?
If I could modify UIWebView, I'd just make the lock attempt non-blocking, but obviously that's not the case, so I'm looking for other clever ideas.
The long and short of it is: avoid doing anything that blocks the web thread for a significant amount of time (window.alert, window.prompt, XMLHttpRequest.open('GET', url, false), possibly others)
Also, avoid calling methods that lock the web thread and then immediately doing something that takes a long time as the web thread is only unlocked once control is returned to the run loop. (Example: call -[UITextView setText:] then read a file synchronously on the main thread)
you cannot make synchronous xhr since this will lead to crossdomain policy errors.