How to access main thread from worker thread in Java? - java

Read many overkilled, overcomplicated solution here in SO, for such an easy question, how to access main thread from a worker thread, to execute some code on it.
In iOS dispatch_get_main_queue() method returns main thread. How in Java?
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0UL), ^{
//do background thread stuff
dispatch_async(dispatch_get_main_queue(), ^{
//update UI
});
});

In Android you can't access the main thread (UI Thread) directly, but you can queue jobs on it, so you need to create a Handler and using that handler to post jobs (Runnable) on main thread.
Below is an example of how you can post on UI Thread using Handler
new android.os.Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
//Doing job here
}
})
and also as #CommonsWare mentioned in the comments, there is another ways to access UI thread:
if you have instance of any View you can use View.post(Runnable)
if you have instance of Activity, you can use Activity.runOnUiThread(Runnable)
Btw accessing main thread in Android is totally different than Java Desktop Apps

Running your code on main thread from another:
runOnUiThread(new Runnable() {
#Override
public void run() {
// Your code here
}
});
Hope this helps

Related

How does an animation work on UI thread without blocking other messages and runnable in message queue of UI Thread?

I am working on some old android code where the code looks something like this:
public void TestMethod() {
// handler posting on main thread
handler.post(() -> {
//Invokes method();
});
animation.addListener(new AnimatatorListenerAdapter(){
#Override
public void onAnimationEnd() {
// Do some stuff;
}
});
animation.start();
}
As per my understanding, the animation life cycle callbacks always execute on UI thread. Since method() is posted first on message queue therefore it should be executed before onAnimationEnd(), but some times (3/10 times) onAnimationEnd executes before method(). Therefore now I am confused about android animation ( Surely I am missing something).
Questions:
What should be the ideal flow in this code?
Between method() and onAnimationEnd(), which one will be executed first and why?
How android animation executes on UI thread without blocking other messages and runnable in the message queue of UI Thread?

What is the best way to wait until a runnable on the main thread completes in Android?

I need to collect a username and password from a user inside WebViewClient#shouldInterceptRequest, so I must block the WebView IO thread until the user supplies a username and password on the main thread. What is the best way to wait until my runnable completes?
My current favorite way is (exceptions and timeouts omitted for brevity):
final CountDownLatch countDownLatch = new CountDownLatch(1);
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
callSomethingWithAsyncCallback(new Runnable() {
public void run() {
countDownLatch.countDown();
}
});
}
});
countDownLatch.await();
Something that uses ExecutorServices seems better since I can simply use Future#get to block. However, there is no ExecutorService that runs on the main thread, and using one from Executors just to bounce it to the main thread seems wasteful. Thoughts?
Please use AsyncTask rather than using runnable.
The AsyncTask executes everything in doInBackground() inside of another thread, which does not have access to the GUI where your views are.
preExecute() and postExecute() offer you access to GUI before and after the heavy lifting occurs in this new thread, you can even pass the result of the long operation to postExecute() to then show any results of processing.

Android managing threads without using AsyncTask

I have a project I am working on where I need to improve my knowledge on Threads.
Scenario:
I have an Activity which calls a method Which use uses a thread:
Object soapResponse = soaphttp.fetchNextCatalogueRange(0, numberOfItems);
In the soaphttp class I have:
Thread soapThread = new Thread(new Runnable()
{
private Object serverResponse = new Object();
public void run()
{
// Do network stuff here
}
});
soapThread.start();
try
{
// crude synchronisation
soapThread.join();
}
The problem
Using join() blocks the UI thread.
If I dont use join() I get null pointer exceptions (data sync errors)
The Challenge:
In my activity I would like to do stuff on the UI thread while the soaphttp class is fetching data and then sync i.e tell the UI thread that the data is ready.
for example display a progress bar .. which will terminate when the data has finished being fetched.
How can I do this without having to use AsyncTask ?
At the very end of your thread's run() method, use one of the following:
the post() method of View class,
the runOnUiThread() method of Activity class
in order to refresh your UI in the UI thread.
You can use the same methods to somehow alter your UI at the start of the run() method (make same widgets disabled, show some kind of progress indicator...)

How to make calling a Method as a background process in java

In my application , I have this logic when the user logins , it will call the below method , with all the symbols the user owns .
public void sendSymbol(String commaDelimitedSymbols) {
try {
// further logic
} catch (Throwable t) {
}
}
my question is that as this task of sending symbols can be completed slowly but must be completed , so is there anyway i can make this as a background task ??
Is this possible ??
please share your views .
Something like this is what you're looking for.
ExecutorService service = Executors.newFixedThreadPool(4);
service.submit(new Runnable() {
public void run() {
sendSymbol();
}
});
Create an executor service. This will keep a pool of threads for reuse. Much more efficient than creating a new Thread each time for each asynchronous method call.
If you need a higher degree of control over your ExecutorService, use ThreadPoolExecutor. As far as configuring this service, it will depend on your use case. How often are you calling this method? If very often, you probably want to keep one thread in the pool at all times at least. I wouldn't keep more than 4 or 8 at maximum.
As you are only calling sendSymbol once every half second, one thread should be plenty enough given sendSymbols is not an extremely time consuming routine. I would configure a fixed thread pool with 1 thread. You could even reuse this thread pool to submit other asynchronous tasks.
As long as you don't submit too many, it would be responsive when you call sendSymbol.
There is no really simple solution. Basically you need another thread which runs the method, but you also have to care about synchronization and thread-safety.
new Thread(new Runnable() {
public void run() {
sendSymbol(String commaDelimitedSymbols);
}
}).start();
Maybe a better way would be to use Executors
But you will need to case about thread-safety. This is not really a simple task.
It sure is possible. Threading is the way to go here. In Java, you can launch a new thread like this
Runnable backGroundRunnable = new Runnable() {
public void run(){
//Do something. Like call your function.
}};
Thread sampleThread = new Thread(backGroundRunnable);
sampleThread.start();
When you call start(), it launches a new thread. That thread will start running the run() function. When run() is complete, the thread terminates.
Be careful, if you are calling from a swing app, then you need to use SwingUtil instead. Google that up, sir.
Hope that works.
Sure, just use Java Threads, and join it to get the results (or other proper sync method, depends on your requirements)
You need to spawn a separate thread to perform this activity concurrently. Although this will not be a separate process, but you can keep performing other task while you complete sending symbols.
The following is an example of how to use threads. You simply subclass Runnable which contains your data and the code you want to run in the thread. Then you create a thread with that runnable object as the parameter. Calling start on the thread will run the Runnable object's run method.
public class MyRunnable implements Runnable {
private String commaDelimitedSymbols;
public MyRunnable(StringcommaDelimitedSymbols) {
this.commaDelimitedSymbols = commaDelimitedSymbols;
}
public void run() {
// Your code
}
}
public class Program {
public static void main(String args[]) {
MyRunnable myRunnable = new MyRunnable("...");
Thread t = new Thread(myRunnable)
t.start();
}
}

Besides AsyncTask, is there anyway in Android to do something on the UI thread from another thread?

Because for some strange reasons, when I use AsyncTask to connect to a webpage, the UI of my app lags to almost the point of freezing while the AsyncTask is connecting to the webpage.
I thought this was because the connection usually takes quite long, at least 4 seconds.
I want to be able to update my TextView after my Thread have finished, but how do I do that in Android besides using AsyncTask?
There are a few methods to do that:
Use Threads or Runnables
Use Handlers, sending messages to its
Use RunOnUIThread method
Use the method (this is my favorite) post. It's not necessary to use a context/activity instance
For example, you can create a new Handler() and when you want to run code in the main thread do:
public static Handler interfaceHandler = new Handler();
...
mInterfaceHandler.post(new Runnable() {
#Override
public void run() {
//Your stuff
}
});
To complete the information, all Views in Android can make this post(Runnable) . This method add a runnable to their task to do, for that reason is recommendable not use views because the App will slow down. The static handler is perfect to make this work and is very easy to implement
Something like this should work
runOnUiThread(new Runnable() {
public void run() {
// do some stuff here
}
});

Categories

Resources