0

I create an HttpURLConnection in a Thread or AsyncTask and it works fine. But when the Device is in sleep mode, (Display is Off...) then I get an Exception by open the Connection -> java.net.ConnectException: Connection refused.

My idea is to wake up the Device with the PowerManager.PARTIAL_WAKE_LOCK, but that doesn't help.

The other defines from PowerManager for example ACQUIRE_CAUSES_WAKEUP are deprecated.

What can I do to create a successful connection?

The code:

URL url = new URL("myUrl...");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
int response = urlConnection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
     // to do some work
 }
peterh
  • 11,875
  • 18
  • 85
  • 108
  • You should consider telling us what you really want to achieve. The code snippet is not enough to guess. BTW, "display off" and "sleep mode" is not exactly the same. A lot of stuff can be configured by the user and you need to consider that (e.g. drop WiFi in sleep mode). Please edit your question and tell us: Why do you want a connection while the device sleeps? Is there a chance that the connection is established while the device is awake but should be used while it is asleep? How much data are you fetching and how often? What do you know about services? – class stacker Jun 07 '17 at 07:58
  • I think your question could look *much* better with only a little [improvement](https://meta.stackoverflow.com/a/291370/1783163). Look, how well it looks after my edit. Also you could do it. – peterh Jun 07 '17 at 17:51
  • I only want a simple http GET and POST request to a server, when the Location of my Smartphone change (every ~4 Minutes). The request Data is less than 100 bytes. It works fine, when the Display is on. After the Display is off the connection can't be open. I know about services. – Jörg Bausch Jun 08 '17 at 09:16

1 Answers1

0

I suggest you to use OkHttp. It is better than HttpClient.

Divakar
  • 21
  • 4