构造函数中处理程序的 postDelay 方法的正确方法

Correct approach for postDelay method of handler in the constructor

我的服务中有以下带有构造函数的线程 class。

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

在我的服务 onCreate 中,我尝试构建线程并启动 it.First 处理程序工作正常,我可以发送消息。由于我想 post 延迟消息,因此在第二个处理程序中我尝试使用 postDelay 方法。这就是问题所在。

    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();

我收到以下错误。我在这里犯了什么愚蠢的错误?还是完全错误的做法。

error: incompatible types: boolean cannot be converted to Handler

错误:incompatible types 是因为:-

handler.postDelayed(runnable) --> returns boolean

而构造函数需要 android.os.Handler

类型的对象

所以你 基本上 传递 boolean 而不是 Handler

的实例

有关更多信息,请查看 android.os.Handler(cmd + 单击)处理程序