Reputation: 1131
I am creating an Android application that needs to constantly send UDP packets to a server.
The problem is that after 2-5 minutes, after the screen is off, the service stops sending data, until I turn the screen back on (can also confirm on the server side).
Here is the service start command:
startService(new Intent(getBaseContext(), Service.class));
The onStartCommand:
@Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(this, "Armed!", Toast.LENGTH_LONG).show();
(new Thread(new App())).start();
return START_REDELIVER_INTENT;
}
And the run method, from the App thread:
public void run(){
Vibrator alarm = (Vibrator) MainActivity.getAppContext().getSystemService(Context.VIBRATOR_SERVICE);
String IP = getWiFiIP(MainActivity.getAppContext());
while(true){
while (IP.equals(wifiAddr)){ //Confirm presence on local network, with host
//Unlocked door
System.out.println("Started locally!");
sendData(KEY, hostAddrLocal);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
IP = getWiFiIP(MainActivity.getAppContext());
}
}
}
I am positive that I am not running out of memory, I have no other applications up, running on Galaxy S4, with Lollipop 5.0
Is it because I am interacting with the main activity, to get the context
MainActivity.getAppContext()
?
I tried many things, including STICKY_SERVICE
.
Upvotes: 0
Views: 552
Reputation: 1006869
The problem is that after 2-5 minutes, after the screen is off, the service stops sending data, until I turn the screen back on (can also confirm on the server side).
The CPU has powered down, as has the WiFi radio, in all likelihood. You would need to acquire a WakeLock
and a WifiLock
to keep both powered on. For ordinary users with ordinary hardware, keeping the CPU and WiFi radio on all the time will be very unpopular due to battery drain.
Upvotes: 3
Reputation: 93614
Android is programmed to fall asleep after inactivity. When that happens, it powers down the processor and doesn't allow any app to process. To be an exception to this rule, you need to hold a partial wakelock. Doing so will cause you to use more battery though so try not to hold it longer than needed.
Upvotes: 2