6

I am viewing the source code for the HandlerThread class and noticed the class contains a data member mHandler. mHandler is an instance of type Handler.

private @Nullable Handler mHandler;

There is an accessor method for getting the instance of the private member defined in the HandlerThread class as well.

@NonNull
public Handler getThreadHandler() {
    if (mHandler == null) {
        mHandler = new Handler(getLooper());
    }
    return mHandler;
}

I tried to get a reference to the mHandler member by calling the method on my HandlerThread reference. AndroidStudio does not allow a method call getThreadHandler on a HandlerThread instance. The method appears to be public just like the other public methods that can be called on a HandlerThread instance. Does anyone know why the public method getThreadHandler can not be called on a HandlerThread instance. Am I just missing something in the class/method/member definition? My code for instantiating a HandlerThread instance and calling methods is shown below.

...

import android.os.*

...

class SearchActivity : AppCompatActivity(), View.OnClickListener {

...

    private val backgroundWork = HandlerThread("BackgroundApiCall")
    private lateinit var backgroundHandler: Handler

    ...

    override fun onCreate(savedInstanceState: Bundle?) {

        ...

        backgroundWork.start()
        backgroundHandler = = Handler(backgroundWork.looper)
        // an attempt here to call getThreadHandler will not work
        val handler = backgroundWork.threadHandler // or .getThreadHandler() for our Java friends
        ...

    override fun onDestroy() {
        super.onDestroy()
        backgroundWork.quit()
    }

    override fun onClick(_searchBtn: View?) {
        backgroundHandler.post(requestWork)
    }

    ....

Note: I am only posting the code that is relative to the problem at hand and not the entire class.

  • 5
    That method has `@hide` in its comment. See [here](https://stackoverflow.com/q/31908205/1435985) for an explanation of what it does and why you cannot directly access the method like other public methods. – George Mulligan Aug 28 '18 at 15:07
  • Thank you! I definitely missed that in the comment block above the method. Thank you again! –  Aug 28 '18 at 15:11
  • @GeorgeMulligan any idea why it was hidden? – Maverick Meerkat Mar 05 '19 at 12:04
  • 1
    @DavidRefaeli Usually it's because you do not need access to the method. There have been cases where people have required access to hidden methods and sometimes they will change the method to make it accessible in later versions. Typically though there is something else you can do that doesn't require accessing the hidden method. In this case if you need a `Handler` that uses the same `Looper` as the `HandlerThread` you can make it yourself. `val myHandler = Handler(myHandlerThread.looper)` – George Mulligan Mar 05 '19 at 14:28

0 Answers0