Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HandlerThread didn't run in background?

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.

like image 299
Juliette_Evans Avatar asked Jul 03 '26 20:07

Juliette_Evans


1 Answers

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.

like image 77
Larry Schiefer Avatar answered Jul 05 '26 08:07

Larry Schiefer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!