大家好,我是android编程的初学者,尝试理解HandlerThread的工作方式时遇到了一些麻烦。具体来说,我不确定每次在添加到线程消息队列的可运行对象中调用该方法时,是否都会在后台线程(或非UI线程)中执行自定义视图类中的方法。
我有一个自定义视图,并且在mainactivity中初始化了HandlerThread:
HandlerThread mainHandlerThread = new HandlerThread("mainhandler");
mainHandlerThread.start();
Handler mainHandler = new Handler(mainHandlerThread.getLooper());
myCustomView mcv = (MyCustomView) findViewById(R.id.customView);
并且在MyCustomView类(扩展视图)中,我有一个称为update()的方法:
public void update(int number, String txt) {
//perform some calculations
invalidate(); //redraw the view
}
每次MainActivity都检测到更改,它将使用mainHandler.post()调用MyCustomView的更新方法:
mainHandler.post(new Runnable() {
@Override
public void run () {
mcv.update(123,"test")
}
});
上面的代码是否导致从HandlerThread(非UI线程)重绘自定义视图?我能够同时使用invalidate()和postInvalidate()来绘制视图,因此我对update()方法是在UI线程上还是在我创建的HandlerThread上运行感到困惑。
mainHandler
使用您创建的looper
的handlerThread
(不是mainLooper)。因此,要在主线程上运行update
方法,请将mainHandler
与Looper.getMainLooper()
关联:-
Handler mainHandler = new Handler(Looper.getMainLooper());