如何在屏幕关闭时在 android 中发出 http 请求?

How to make an http request in android when screen is off?

我在屏幕关闭时发出 HTTP 请求时遇到了一些麻烦。我目前通过以下方式使用 HttpUrlConnection:

class HttpPostRequest extends AsyncTask<String, Void, String> {

     private String httpResponse = null;

     public String getResponse() {
         return httpResponse;
     }

     @Override
     protected String doInBackground(String... params) {
        try {

                URL url = new URL(params[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

                connection.setDoOutput(true);
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
                writer.write(params[1]);
                writer.flush();
                writer.close();

                connection.connect();

                Log.e("Response", connection.getResponseCode() + "");
                Log.e("Url", connection.getRequestMethod());

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { //success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                connection.disconnect();

                // print result
               return response.toString();
            }

        } catch (Exception e) {
            Log.e(e.toString(), "Something with request");
            return "";
        }
        return "";
    }
}

然而,虽然当我正在编写的应用程序在屏幕上时它工作得很好,但当屏幕关闭时它无法工作。很高兴听到社区的建议。谢谢!

使用 Thread 而不是 AsyncTask 例如

Thread t = new Thread({
   public void run(){
      .....
      your code
      } 
   });
t.start();

如果你想在后台调用http请求,可以使用WorkManager。欲了解更多信息,您可以访问https://developer.android.com/topic/libraries/architecture/workmanager