2017-06-13 97 views
1

我一直在使用有線智能卡閱讀器SDK,其中的調用同步。最近一直在嘗試藍牙接口,但APDU命令是異步的,因此我們無法解釋爲形成下一個APDU命令而發送的呼叫的響應。APDU命令異步調用

任何幫助將不勝感激。

請求

byte[] var1 = {(byte)0, (byte)-92, (byte)4, (byte)0, (byte)12, (byte)-96, (byte)0, (byte)0, (byte)2, (byte)67, (byte)0, (byte)19, (byte)0, (byte)0, (byte)0, (byte)1, (byte)1}; 

     String apduString = QPOSUtil.byteArray2Hex(var1); 
     pos.sendApdu(apduString); 

結果:

@Override public void onReturnApduResult(boolean arg0, String arg1, int arg2) { }

+0

[將異步計算包裝爲同步(阻塞)計算]的可能副本(https://stackoverflow.com/questions/2180419/wrapping-an-asynchronous-computation-into-a-synchronous-blocking-computation) –

回答

0

您可以膠囊你異步調用一個同步。主要想法是在等待結果時阻止當前線程。我喜歡使用鎖,所以我使用java.util.concurrent.locks.ReentrantLock。但有很多方法可以實現此行爲,如java.util.concurrent.Future<T>Busy Waiting

// Lock that is used for waiting 
private final ReentrantLock waitLock = new ReentrantLock(); 

private APDUResult result = null; 

// synchronous wrapper 
// synchronized keyword is used to serialize requests 
public synchronized APDUResult sendAPDUSynchronous(byte[] apdu) { 
    // calles asynchronous function 
    sendAPDUAsynchronous(apdu); 
    // waits until .unlock() is called 
    waitLock.lock(); 
    // returns the result 
    return result; 
} 

// this function sould not be called outside - so its private 
private void sendAPDUAsynchronous(byte[] apdu) { 
    String apduString = QPOSUtil.byteArray2Hex(var1); 
    pos.sendApdu(apduString); 
} 

@Override 
public void onReturnApduResult(boolean arg0, String arg1, int arg2) { 
    // stores the result 
    result = new APDUResult(arg0, arg1, arg2); 
    // notifys the waiting thread in synchronous call 
    waitLock.unlock(); 
} 

APDUResult只是包裝的三個參數來一個對象,可以passted作爲由同步功能。不要忘記在錯誤回調中調用waitLock.unlock()。否則會出現僵局。

還有其他posts這個話題也應該你需要更多的靈感。