Java – HandlerThread not running in the background?

HandlerThread not running in the background?… here is a solution to the problem.

HandlerThread not running in the background?

I’m trying to learn how to run in the background using HandlerThread. I have a button in the fragment that, after clicking it, I want to get the number of entries from the database. But when I actually ran it, logcat said the app might be doing too much work on the main thread, and I don’t know what I’m doing wrong.

Here’s how I arrange the code in 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 I’m doing anything wrong , which still blocks the UI at runtime.

Solution

Remove it from your Runnable:

handler.post(new Runnable() {

You’re publishing your Runnable, which in turn just posts the Runnable back to the main thread. So your main thread is still doing all the work.

Related Problems and Solutions