[英]How can I send http requests when phone state changes?
我正在偵聽PhoneStateListener上的更改,並且每次發生更改時都想發出一個url請求。 我將不勝感激。
我試圖擺弄下面的代碼沒有成功。 日志消息工作正常,但對Web服務器的請求不起作用。
private class PhoneCallListener extends PhoneStateListener{
private boolean isPhoneCalling = false;
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state)
{
// phone ringing
Log.i("LOG_TAG", "RINGING, number: " + incomingNumber);
try {
URL url = new URL("http://example.com/log.php?state=Ringing");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.disconnect();
}
catch (MalformedURLException ex) {
Log.e("httptest",Log.getStackTraceString(ex));
}
catch (IOException ex) {
Log.e("httptest",Log.getStackTraceString(ex));
}
Log.i("LOG_TAG", "RINGING, number: " + incomingNumber);
}
}
}
您可能沒有權限https://developer.android.com/training/permissions/requesting
並嘗試在輔助線程中運行http io代碼:
private class PhoneCallListener extends PhoneStateListener {
private boolean isPhoneCalling = false;
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state)
{
new AsyncTask<String,Void,Void>(){
@Override
protected Void doInBackground(String... voids) {
// phone ringing
String incomingNumber=voids[0];
Log.i("LOG_TAG", "RINGING, number: " + incomingNumber);
try {
URL url = new URL("http://example.com/log.php?state=Ringing");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.disconnect();
}
catch (MalformedURLException ex) {
Log.e("httptest",Log.getStackTraceString(ex));
}
catch (IOException ex) {
Log.e("httptest",Log.getStackTraceString(ex));
}
Log.i("LOG_TAG", "RINGING, number: " + incomingNumber);
return null;
}
}.execute(incomingNumber);
}
}
}
還查看是否存在網絡問題; 例如dns,訪問策略,路由問題...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.