So I create a Socket in my Service which is started from an Activity. Socket connects to my server and waits for messages which aren’t periodical, they are sent when i write them in. Messages are received fine at first when the Service is started but after I leave the phone alone and don’t send any messages, when the screen goes blank an IO exception goes off for the InputStream.readLine() meaning the socket’s dead I suppose. The process is still running and continues to run when this happens. Is this normal behavior? I thought I’d get at least 20, 30 mins before the Socket dies, not few seconds.
Socket mSocket=new Socket(InetAddress.getByName("192.168.1.104"),4444);
BufferedReader in=new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
String message;
try {
while((message=in.readLine())!=null){
notify(message);
}
} catch (IOException e) {
notify("socket dead");
}
You can use the
WifiManager(http://developer.android.com/reference/android/net/wifi/WifiManager.html) to obtain aWifiLockto keep the network available even after the screen goes off.And once it is no longer needed:
You will need to add the
android.permission.WAKE_LOCKpermission to your manifest.Be aware that this will probably be pretty hard on battery life.