2013-08-20 51 views
0

我正在製作一個應用程序,當撥出某個號碼(我們稱之爲123456789)時,它會嘗試將HTTP郵件發送到帶有幾位數的URL等待一個好的,然後讓這個電話通過。在Android撥出電話上暫停併發送HTTP信息

但是,如果此HTTP POST花費的時間比4秒鐘長,那麼我們將數字作爲DTMF添加到外發號碼上。

問題是,在Android上,主線程不應該(或不能)進入睡眠狀態,否則手機會變得沒有響應,然後崩潰,所以我需要找一個等待延遲通話時間爲4秒,而我做POST。

下面是代碼的樣子。我不打算採用特定的代碼行,但我更傾向於在撥打電話之前弄清楚如何讓手機等待郵政的結果。

public class OutgoingCallReceiver extends BroadcastReceiver { 

public void onReceive(Context pContext, Intent intent) { 

Context context = pContext; 
String action = intent.getAction(); 

String digitsToSend = ",1234"; 
String outgoingNumber = getResultData(); 

if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL) 
    && isNetworkAvailable(pContext) 
     && outgoingNumber.equals("123456789") { 

    try{ 
     //We set a HTTPConnection with timeouts, so it fails if longer than 4  seconds 
     HttpParams httpParameters = new BasicHttpParams(); 
     HttpConnectionParams.setConnectionTimeout(httpParameters, 2000); // allow 2 seconds to create the server connection 
     HttpConnectionParams.setSoTimeout(httpParameters, 2000); // and another 2 seconds to retreive the data 
     HttpClient client = new DefaultHttpClient(httpParameters); 

     HttpGet request = new HttpGet(url); 
     HttpResponse response = client.execute(request); 

     HttpEntity entity = response.getEntity(); 
     if (response.getStatusLine().getStatusCode() == 200){ 
      //Success 
      setResultData(outgoingNumber); 
     } 

    } catch (Exception e){ 
      //Took too long, sending digits as DTMFs 
     setResultData(outgoingNumber+digitsToSend); 
    } 
} 
} 

回答

0

你有2個可能的解決方案: 要麼使用回調和實現它們從您的主要活動調用一個方法中,這樣的請求結束時,你可以用代碼從那裏出發。 (最好的解決方案) 或者你也可以配合countdownlatch,它基本上就像一個紅色的交通燈,在你釋放它之前「停止」代碼。以下是它的工作方式:

final CountDownLatch latch = new CountDownLatch(1); // param 1 is the number of times you have to latch.countDown() in order to unlock code bottleneck below. 

latch.countDown(); // when you trigger this as many times as set above, latch.await() will stop blocking the code 


try { 
      latch.await(); //wherever u want to stop the code 
    }catch (InterruptedException e) { 
      //e.printStackTrace(); 
    } 
相關問題