在另一个线程的UI线程中执行某些操作并等待完成

时间:2014-05-02 06:42:51

标签: android

我的代码是从AsyncTask.doInBackground()调用的,但我需要使用一个对象,其方法应该从UI线程调用。

我猜,我可以使用Handler执行此操作,但是没有send()方法,只有post()方法不会等待。

public class Synchronizer implements PlayerInterface {

    private final PiterFMPlayer playerInstance = new PiterFMPlayer();
    private final Handler handler = new Handler();

    @Override
    public void open(final String channelId, final String trackTime) {
        handler.send(new Runnable() {
            @Override
            public void run() {
                playerInstance.open(channelId, trackTime);
            }
        });
    }

我甚至想到锁定/通知:

public class Synchronizer implements PlayerInterface {

    private final PiterFMPlayer playerInstance = new PiterFMPlayer();

    @Override
    public void open(final String channelId, final String trackTime) {
        new MySender() {
            @Override
            public void run2() {
                playerInstance.open(channelId, trackTime);
            }
        };
    }

    private final Handler handler = new Handler();
    private final Object lock = new Object();
    private RuntimeException runtEx;

    private abstract class MySender implements Runnable {
        public MySender() {
            if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
                run2();
            } else {
                runtEx = null;
                synchronized(lock) {
                    handler.post(this);
                    try { lock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); }
                }
                if (runtEx != null) throw runtEx;
            }
        }

        @Override
        public final void run() {
            try {
                run2();
            } catch (RuntimeException e) {
                runtEx = e;
            }
            synchronized(lock) {
                lock.notify();
            }
        }
        public abstract void run2();
    }

也许我可以使用Future.get()而不是自己调用wait()

1 个答案:

答案 0 :(得分:0)

使用AsyncTask.execute()。get(),您将等到doInBackground()结束。

http://developer.android.com/reference/android/os/AsyncTask.html