我正在制作一个应用程序,当对某个号码(我们称之为 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);
}
}
}