Juliette_Evans
Juliette_Evans

Reputation: 232

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.

Upvotes: 3

Views: 688

Answers (2)

Chandan Dwivedi
Chandan Dwivedi

Reputation: 1

Modify runnable like this:-

private Runnable myRunnable=new Runnable() {
@Override
public void run() {
      List<Item> list=db.getAllItems();
      Log.d(TAG,"Size: "+list.size());
}};

Upvotes: 0

Larry Schiefer
Larry Schiefer

Reputation: 15775

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.

Upvotes: 3

Related Questions