Using HandlerThread and Handler on a separate thread freezes UI thread

一世执手 提交于 2019-12-07 05:46:25

Try this:

Just wrap your first runnable in a Thread.

public class MyManager{
private MyManager sInstance;
private HandlerThread mHandlerThread;
private Handler mHandler;
private Runnable mTimeoutTimer;

public static MyManager getInstance(){
    if(sInstance == null){
        sInstance = new MyManager();
    }
    return sInstance;
}

private MyManager(){
    mHandlerThread = new HandlerThread();
    mHandler = new Handler(mHandlerThread.getLooper());
    mTimeoutTimer = new Runnable() {
        @Override
        public void run() {
            Log.e(“RUNNABLE RUNNING!”);
        }
};

public class MyCommand {
    private Thread th;
    private Runnable myRun;

   public MyCommand(){
       myRun = new Runnable() {
           @Override
           public void run() {
               MyManager.getInstance().startTimeoutTimer();

               try {
                   Thread.sleep(COMMAND_TIMEOUT_MILLIS * 3);
               } catch (InterruptedException e) {}

               MyCommand.this.execute();
           }
       };
       th = new Thread(myRun);
   }

   public void execute() {
       th.start();
        mHandler.postDelayed(mTimeoutTimer);
   }
}


private void startTimeoutTimer(){
    mHandlerThread.start();
    mHandler.postDelayed(mTimeoutTimer);

}


public void startCommand(){
    new MyCommand().execute();
}

}

Also you forgot to start the mHandlerThread

    private void startTimeoutTimer(){
    mHandlerThread.start();
    mHandler.postDelayed(mTimeoutTimer);

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!