0

我正在制作一个应用程序,当对某个号码(我们称之为 123456789)进行拨出呼叫时,它将尝试将 HTTP 帖子发送到带有几位数字的 URL 并等待 OK,然后让呼叫通过。

但是,如果此 HTTP POST 花费的时间超过 4 秒,那么我们会将数字作为 DTMF 添加到传出号码上。

问题是,在 Android 上,主线程不应该(或不能)进入睡眠状态,否则手机会变得无响应然后崩溃,所以我需要等待来延迟由4 秒,而我做 POST。

这是代码的样子。我不打算使用特定的代码行,但我更想弄清楚如何让电话在拨打电话之前等待 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);
    }
}
}
4

1 回答 1

0

您有两种可能的解决方案:使用回调并在您从主活动调用的方法中实现它们,以便在请求结束时,您可以从那里继续处理代码。(最佳解决方案)或者您也可以使用 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();
    }
于 2013-11-18T15:50:24.743 回答