Java handlerthread is not running in the background?

I'm trying to learn how to use handlerthread to run things in the background. I have a button in the clip. When I click this button, I want to get the number of entries from the database. But when I actually run it, logcat says that the application may do too much work on the main thread, and I don't know what I've done wrong

This is how I arrange the 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 did wrong, and it still blocks the UI at run time

resolvent:

Remove it from your runnable:

handler.post(new Runnable() {

You are publishing your runnable, which sends it back to the main thread. Therefore, your main thread is still performing all work

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>