user1154267
user1154267

Reputation: 33

Android socket gets killed imidiatelly after screen goes blank

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

Upvotes: 1

Views: 3049

Answers (3)

Adam
Adam

Reputation: 6117

Acquire both a Wifi Lock and Power Wakelock. On Android 4.0 I am able to turn the screen off with my socket listening and then send data to the socket from an external server every 10 minutes.

WifiManager wMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiManager.WifiLock wifiLock = wMgr.createWifiLock(WifiManager.WIFI_MODE_FULL, "MyWifiLock");
wifiLock.acquire();

PowerManager pMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();

When they are no longer needed:

wifiLock.release();
wakeLock.release();

Ensure you have the android.permission.WAKE_LOCK permission. It may also be necessary to have the user set their Wifi to "Never Sleep" in the Android Wifi Manager.

Upvotes: 1

j2emanue
j2emanue

Reputation: 62549

Try this:

private void setNeverSleepPolicy(){
    ContentResolver cr = _context.getContentResolver();
    int set = android.provider.Settings.System.WIFI_SLEEP_POLICY_NEVER;
    Boolean didchangepolicy=android.provider.Settings.System.putInt(cr, android.provider.Settings.System.WIFI_SLEEP_POLICY, set);
    Log.v(TAG,didchangepolicy?"changed policy":"did not change policy");
}

and google wifi sleep policy it might help

Upvotes: 1

Brigham
Brigham

Reputation: 14544

You can use the WifiManager (http://developer.android.com/reference/android/net/wifi/WifiManager.html) to obtain a WifiLock to keep the network available even after the screen goes off.

WifiManager.WifiLock lock = ((WifiManager) someContext.getSystemService(Context.WIFI_SERVICE)).createWifiLock("MyWifiLock")

And once it is no longer needed:

lock.release();

You will need to add the android.permission.WAKE_LOCK permission to your manifest.

Be aware that this will probably be pretty hard on battery life.

Upvotes: 3

Related Questions