手机状态更改时如何发送http请求?

时间:2019-02-03 11:11:24

标签: java android httpurlconnection phone-state-listener

我正在侦听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);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

您可能没有权限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,访问策略,路由问题...