I'm trying to learn how to use HandlerThread to run things in background. I have a button in a fragment that when clicked, I want to get the number of entries from a database. But when I actually run it, logcat says the application may be doing too much work on the main thread, and I don't know what I did wrong.
Here's how I arranged my code in the fragment:
private Handler handler=new Handler();
private MyWorkerThread myWorkerThread;
private Runnable myRunnable=new Runnable() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
List<Item> list=db.getAllItems();
Log.d(TAG,"Size: "+list.size());
}
});
}
};
private class MyWorkerThread extends HandlerThread{
private Handler myHandler;
private MyWorkerThread(String name) {
super(name);
}
private void postTask(Runnable task){
myHandler.post(task);
}
private void setMyHandler(){
myHandler=new Handler(getLooper());
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myWorkerThread=new MyWorkerThread("myWorkerThread");
myWorkerThread.start();
myWorkerThread.setMyHandler();
}
@OnClick(R.id.btn)
void getCount(){
myWorkerThread.postTask(myRunnable);
}
I'm following the example in this blog post, but I'm not sure what I'm doing wrong and it still blocks the UI while running.
Remove this from your Runnable:
handler.post(new Runnable() {
You are posting your Runnable which in turn just posts a Runnable back to the main thread. So your main thread is still doing all the work.
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