My code was invoked from AsyncTask.doInBackground()
, but I need to use an object whose methods should be called from the UI thread.
I gues, I can do this with Handler, but there's no send()
method, only post()
method that doesn't wait.
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);
}
});
}
I'm even thinking now of lock/notify:
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();
}
Maybe I could use Future.get()
instead of calling wait()
myself