Search code examples
androidhandlerandroid-handler

Correct approach for postDelay method of handler in the constructor


I have the following thread with a constructor in my service class.

public class communicationDetails extends Thread {
    communicationDetails(final Handler _handler, final Handler conn_handler) throws IOException {
        mhandler = _handler;
        connHandler = conn_handler;
    }

In onCreate in my service I tried to construct the thread and start it.First handler works fine, I could able to send messages. Since I want to post a message with delay, in the second handler I am trying to use postDelay method. This is where the problem comes in.

    try {
        communication_Details = new communicationDetails(
                // works fine
                new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(final Message msg) {
                        // sending messages
                    }
                }, 

                //this throws an error
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                      // call a method
                    }
                }, 2000));
        } catch (IOException e) {
            e.printStackTrace();
        }

    communication_Details.start();

I get following error. What stupid mistake am I doing here ? or is it completely wrong approach.

error: incompatible types: boolean cannot be converted to Handler


Solution

  • The error : incompatible types is because :-

    handler.postDelayed(runnable) --> returns boolean
    

    while the constructor requires object of type android.os.Handler

    So you are basically passing boolean instead of an instance of Handler

    For more info checkout android.os.Handler. ( cmd + click ) on Handler