如何从服务启动的Handler跳转到服务的线程?

时间:2016-10-26 08:58:39

标签: android multithreading service

我在Service类中使用Handler来完成一些后台工作,但是当它完成后,我必须在Service的线程上执行一些代码。这是我的代码:

我在Service的onCreate方法中创建了一个处理程序。

    HandlerThread handlerThread = new HandlerThread(getPackageName());
    handlerThread.start();
    Looper looper = handlerThread.getLooper();
    mHandler = new Handler(looper);

我如何使用处理程序。在会话期间,此方法会被调用数十次。

    mHandler.post(new Runnable() {
        @Override
        public void run() {
              // It takes a few seconds to execute this method, 
              // so it must be running on a separate thread.
              Object o = superMethod();

              // However, this MUST be called from the Service's thread.
              useObject(o);
        }
    };)

那我怎样才能回到服务的主题?

1 个答案:

答案 0 :(得分:0)

服务本身在主线程上运行,你想要从Handler Thread(后台线程)切换到服务(主线程)。

public class SomeService {

    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void doSomething() throws InterruptedException {
        Thread taskThread = new TaskThread();
        taskThread.start();
        taskThread.join(120 * 000);
        if(taskThread.isAlive()) {
            // We timed out
            taskThread.interrupt();
        }
    }

    private class TaskThread extends Thread {

        public void run() {
            // Do the actual work here
        }
    }
}