I\'m new to Android and I\'m trying to use the UI-Thread, so I\'ve written a simple test activity. But I think I\'ve misunderstood something, because on clicking the button
Below is corrected Snippet of runThread
Function.
private void runThread() {
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
This is how I use it:
runOnUiThread(new Runnable() {
@Override
public void run() {
//Do something on UiThread
}
});
We use Worker Thread to make Apps smoother and avoid ANR's. We may need to update UI after the heavy process in worker Tread. The UI can only be updated from UI Thread. In such cases, we use Handler or runOnUiThread both have a Runnable run method that executes in UI Thread. The onClick method runs in UI thread so don't need to use runOnUiThread here.
Using Kotlin
While in Activity,
this.runOnUiThread {
// Do stuff
}
From Fragment,
activity?.runOnUiThread {
// Do stuff
}
Using Java,
this.runOnUiThread(new Runnable() {
void run() {
// Do stuff
}
});
runOnUiThread(new Runnable() {
public void run() {
//Do something on UiThread
}
});
thy this:
@UiThread
public void logMsg(final String msg) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
}
You have it back-to-front. Your button click results in a call to runOnUiThread()
, but this isn't needed, since the click handler is already running on the UI thread. Then, your code in runOnUiThread()
is launching a new background thread, where you try to do UI operations, which then fail.
Instead, just launch the background thread directly from your click handler. Then, wrap the calls to btn.setText()
inside a call to runOnUiThread()
.