Search code examples
androidandroid-studiohttphttpurlconnection

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


I am having quite a bit of trouble making an HTTP request when the screen is turned off. I am currently using HttpUrlConnection in the following way:

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 "";
    }
}

However, while this is working perfectly when the app I am programming is on the screen, it fails to work when the screen is off. It would be great to hear the community's suggestions. Thanks!


Solution

  • use Thread instead of AsyncTask e.g

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