2

Hi all I am a beginner in android programming and I am having a little trouble trying to understand how HandlerThread works. Specifically, I am not sure if the method in the custom view class is executed in the background thread (or non-UI thread) whenever I call the method in a runnable that is added to the thread's message queue.

I have a custom view and HandlerThread initialized in mainactivity:

HandlerThread mainHandlerThread = new HandlerThread("mainhandler");
mainHandlerThread.start();
Handler mainHandler = new Handler(mainHandlerThread.getLooper());
myCustomView mcv = (MyCustomView) findViewById(R.id.customView);

And in MyCustomView class (which extends view), i have a method called update():

public void update(int number, String txt) {
    //perform some calculations
    invalidate(); //redraw the view
}

Everytime MainActivity detects a change, it will use mainHandler.post() to call MyCustomView's update method:

mainHandler.post(new Runnable() {
    @Override
    public void run () {
        mcv.update(123,"test")
    }
});

Does the above code cause the custom view to be redrawn from the HandlerThread(which is a non-UI thread)? I was able to draw the view using both invalidate() and postInvalidate(), hence I am confused on whether the update() method is running on the UI-thread or on the HandlerThread I created.

Santanu Sur
  • 10,997
  • 7
  • 33
  • 52
f00l
  • 21
  • 1
  • I bet you could answer this yourself if you dumped the value of `Thread.currentThread()` inside `update()`, or, better yet, if you set a breakpoint inside `update()`. – greeble31 Jan 20 '20 at 16:32
  • I retrieved `Thread.currentThread()` and called `getName()`, it does indeed say that the current thread is the HandlerThread I created. But why am I still able to call `invalidate()` to redraw the view when I read that `postinvalidate()` should be used for non-UI threads? – f00l Jan 20 '20 at 16:56
  • Apparently you _can_, but you _shouldn't_. I just checked the [source code](https://android.googlesource.com/platform/frameworks/base/+/a175a5b/core/java/android/view/View.java#8549), and I didn't see the thread check. Also see [here](https://stackoverflow.com/questions/46067367/why-is-no-exception-thrown-when-operating-ui-in-a-background-thread-in-previous). – greeble31 Jan 20 '20 at 17:23

0 Answers0