首页 > 解决方案 > Android HTTP Post 请求在后台

问题描述

我有一种方法可以检测调用状态并将其发送到数据库,但仅限于前台活动时。当应用程序处于后台时,我如何继续工作?我应该如何以及应该更改什么以便在应用程序进入后台时运行它?

这里我在 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);
                }
            }
        });
    }

标签: androidservicebackgroundhttp-postandroid-background

解决方案


推荐阅读