【问题标题】:How to make an http request in android when screen is off?屏幕关闭时如何在android中发出http请求?
【发布时间】:2020-10-05 10:19:07
【问题描述】:

当屏幕关闭时,我在发出 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 "";
    }
}

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

【问题讨论】:

  • 它是如何工作的?你有例外吗?

标签: android android-studio http httpurlconnection


【解决方案1】:

使用 Thread 代替 AsyncTask 例如

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-28
      • 2021-07-20
      • 1970-01-01
      • 2013-03-20
      • 2016-04-30
      • 2011-12-19
      • 1970-01-01
      • 2011-12-23
      相关资源
      最近更新 更多