Android HTTP Post请求在后台

时间:2018-11-22 05:38:11

标签: android service background http-post android-background

我有一个检测呼叫状态并将其发送到DB的方法,但是仅当前台有活动时才可以。当应用处于背景状态时,如何继续使用方法?我应该如何更改以及什么更改,以便在应用程序进入后台时可以运行?

我在MainActivity的onCreate()中调用方法:

callStateListener = new PhoneStateListener() {
            public void onCallStateChanged(final int state, String incomingNumber) {

                switch (state){
                    case TelephonyManager.CALL_STATE_IDLE:
                        Log.i(TAG, "onCallStateChanged: IDLE = "+state);
                        if (token!=null) {
                            updateState(token, String.valueOf(state));
                        }else {
                            Log.i(TAG, "onCallStateChanged: ERROR");
                        }
                        break;

                    case TelephonyManager.CALL_STATE_RINGING:
                        Log.i(TAG, "onCallStateChanged: RING = "+state);
                        if (token!=null) {
                            updateState(token, String.valueOf(state));
                        }
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        Log.i(TAG, "onCallStateChanged: CALL = "+state);
                        if (token!=null) {
                            updateState(token, String.valueOf(state));
                        }
                        break;
                }
            }
        };

这是方法:

private void updateState(String token, String state) {
        Log.i(TAG, "updateState: state"+state);
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("token", token)
                .add("state", state)
                .build();

        Request request = new Request.Builder()
                .url("http://update.php")
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("OkHttp", call.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseStr = response.body().string();
                    Log.d("OkHttp", responseStr);
                }
            }
        });
    }

0 个答案:

没有答案