在Android拨出电话上暂停并发送HTTP帖子

时间:2013-08-20 09:02:29

标签: android broadcastreceiver http-post

我正在创建一个应用程序,当拨打某个号码(我们称之为123456789)时,它会尝试将HTTP帖子发送到几位数的URL并等待一个OK,然后让通过呼叫。

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

问题是,在Android上,主线程不应该(或不能)进入睡眠状态,或者 否则手机将无法响应然后崩溃,所以我需要等待,以便在我执行POST时将呼叫延迟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);
    }
}
}

1 个答案:

答案 0 :(得分: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();
    }