I need to accept data using a ServerSocket which is in thread that is in a Background service ServerSocket accepts data fine when the device [Galaxy s3 19300, Android 4.1.2] is in WAKE state. But ServerSocket doesn't seems to accept when the device is in SLEEP mode, ie when the screen is turned off.
I tried using WIFI locks, full and partial and also POWER locks, but both options couldn’t make the ServerSocket listen.
Any clues to solve this folks?
The code
// -------------------------------------------------------------------------
private void CallSock() {
Log.i("$$$$$",
"Before WiFI State is " + Integer.toString(wm.getWifiState()));
wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "MyWifiLock");
PowerManager mgr = (PowerManager) mContext
.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakeLock");
wakeLock.acquire();
if (!wifiLock.isHeld()) {
wifiLock.acquire();
Log.i("$$$$$", "Wifi lock acquired");
}
Looper.prepare();
sSocket = new ServerSocket(serverPort);
while (true) {
Log.i("$$$$$", "In the While loop WiFI State is "
+ Integer.toString(wm.getWifiState()));
Rulecontent.writeLogInfo("Waiting to recieve file");
String fileName = readFile();
}
}
// -------------------------------------------------------------
public String readFile() {
StringBuilder x = null;
try {
InputStream in = null;
Socket recvClientSocket = sSocket.accept();
in = recvClientSocket.getInputStream();
byte[] bytes = new byte[1024];
x = new StringBuilder();
int numRead = 0;
while ((numRead = in.read(bytes)) >= 0) {
x.append(new String(bytes, 0, numRead));
}
} catch (IOException e) {
e.printStackTrace();
}
return x.toString();
}
// -------------------------------------------------------------------------
Ensure that you have the android.permission.WAKE_LOCK
permission and the user has set their Wifi settings to "Never Sleep" in the Android Wifi Manager.
I have verified that ServerSocket
works with the screen off in Android 4.0 in a standard Thread (launched by an Activity) -- I have not tried it as a Background Service. I am able to send commands to my phone every 10 minutes from an external server.
Code snippet for acquiring the Wifi and Power locks, which are both required: