暂停并发送Android传出呼叫的HTTP post

暂停并发送Android传出呼叫的HTTP post,android,broadcastreceiver,http-post,Android,Broadcastreceiver,Http Post,我正在制作一个应用程序,当对某个号码(我们称之为123456789)进行传出呼叫时,它将尝试向一个只有几个数字的URL发送HTTP post,并等待OK,然后让呼叫通过 但是,如果此HTTP POST花费的时间超过(比如)4秒,那么我们将数字添加为传出号码上的DTMFs 问题是,在Android上,主线程不应该(或不能)休眠,或者 否则,手机将失去响应,然后崩溃,所以我需要找到一个等待,以延迟通话4秒,而我做的职位 下面是代码的大致情况。我不打算说具体的代码行,但我更想弄清楚如何让电话在接通电话

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

但是,如果此HTTP POST花费的时间超过(比如)4秒,那么我们将数字添加为传出号码上的DTMFs

问题是,在Android上,主线程不应该(或不能)休眠,或者 否则,手机将失去响应,然后崩溃,所以我需要找到一个等待,以延迟通话4秒,而我做的职位

下面是代码的大致情况。我不打算说具体的代码行,但我更想弄清楚如何让电话在接通电话之前等待帖子的结果

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);
    }
}
}

您有两种可能的解决方案: 或者使用回调并在从主活动调用的方法中实现它们,这样当请求结束时,就可以从那里继续执行代码。(最佳解决方案) 或者你也可以使用倒计时锁存器,它基本上就像一个红色的交通信号灯,它会“停止”代码直到你释放它。下面是它的工作原理:

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();
    }