I have, to my knowledge, implemented a runnable which is created on a new thread. However, the thread does not seem to be running in the background, and the actions taken inside the runnable are stalling the UI with heavy actions.
See below:
custListLoadThread = new Thread(loadRunnable);
custListLoadThread.run();
private Runnable loadRunnable = new Runnable()
{
@Override
public void run()
{
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
Gen.popup("TEST"); // Creates a toast pop-up.
// This is to know if this runnable is running on UI thread or not!
try
{
customers = Db.BasicArrays.getCustomers(CustomApp.Session.businessCode, empId);
runOnUiThread(new Runnable() {
@Override
public void run() {
populate();
setCustListVisible(true);
loading = false;
}
});
}
catch (final Exception ex)
{
runOnUiThread(new Runnable() {
@Override
public void run() {
Gen.popup(ex.getMessage());
}
});
}
}
};
However this code does not run in the background, it still seems to run on the UI thread. I have placed the line Gen.popup("TEST");
to make sure of this (calling a toast
pop up in a non-UI thread should cause an error).
Any ideas as to why this runnable isn't running in the background?
To specify the thread on which to run the action, construct the Handler using a Looper for the thread. A Looper is an object that runs the message loop for an associated thread. Once you've created a Handler , you can then use the post(Runnable) method to run a block of code in the corresponding thread.
Using BroadcastReceiver So you can use it to update the UI on the main thread. For example. Send data from a background thread. This method is usually used to communicate between Android apps or Android apps with the system.
Purpose of the Handler class. A Handler object registers itself with the thread in which it is created. It provides a channel to send data to this thread, for example the main thread. The data which can be posted via the Handler class can be an instance of the Message or the Runnable class.
custListLoadThread = new Thread(loadRunnable);
custListLoadThread.start();
You need to start the thread, not call the run() method in the current thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With