同步处理程序线程

时间:2018-03-22 12:43:44

标签: java android android-handler

我正在运行一个运行一些代码的递归处理程序。我使用HandlerThread发布处理程序。我想在完成上一次调用后才运行下一个递归调用。 有可能这样做吗?如果不是什么选择。

    HandlerThread ht = new HandlerThread();
    ht.start();
    Handler h = new Handler(ht.getLooper());
    h.post(new Runnable() {
         @override
         public void run(){
              //Some code
              h.postDelay(this,1000);
         }
    });

1 个答案:

答案 0 :(得分:1)

您的代码应该可以运行,但是如果您想要一个完整的示例,如何使用HandlerThread以递归方式运行某些内容,请执行以下操作:

public class Main2Activity extends AppCompatActivity {

    private MyWorkerThread mWorkerThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        mWorkerThread = new MyWorkerThread("myWorkerThread");
        final Runnable task = new Runnable() {
            @Override
            public void run() {
                Log.d("TAG", "Done.");
                mWorkerThread.postTask(this);
            }
        };
        mWorkerThread.start();
        mWorkerThread.prepareHandler();
        mWorkerThread.postTask(task);
    }

    @Override
    protected void onDestroy() {
        mWorkerThread.quit();
        super.onDestroy();
    }
}

class MyWorkerThread extends HandlerThread {

    private Handler mWorkerHandler;

    public MyWorkerThread(String name) {
        super(name);
    }

    public void postTask(Runnable task){
        mWorkerHandler.postDelayed(task, 1000); // set timeout which needed
    }

    public void prepareHandler(){
        mWorkerHandler = new Handler(getLooper());
    }
}

请勿忘记致电handlerThread.quit()

中的onDestroy