アクティビティ内の単純なアプリケーションで直接使用されることを前提とした既存の API を使用する必要があります。私のユース ケースでは、Service 内から API を呼び出し、必要な Handler が必要なデータを返すのを待つ必要があります。
Java Concurrency オプションの多くを試しましたが、成功しませんでした。誰でもより良いアプローチを提案できますか?
以下は、実際の例よりも疑似コードである大幅に単純化された例です。
public class dataConnection {
Controlx xControl;
CountDownLatch doneSignal = new CountDownLatch(1);
Context c = null;
private String data1;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
setReturnData(msg);
doneSignal.countDown();
}
};
public dataConnection(Context ctx) {
this.c = ctx;
xControl = new Controlx (c, mHandler);
}
private void setReturnData(int rc) {
this.rc = rc;
}
private int getReturnData() {
return this.rc;
}
public int getRealData() {
//API will timeout in 10 seconds if data is not retrieved before that
xControl.dataCmd(10);
//Wait here for handler to finish and then retrieve data to return
doneSignal.await();
int i = getReturnData();
Log.v("log_tag", "RETURN NOW!!!!!!!!!!!!!!!");
return data;
}