I have a service which works with LongPoll and when I receive my data everything is OK, but when I don't receive data, rather I receive empty result (long polling max time == 25 sec) my service sometimes turning off manually (and I don't see it in list of services).
So, how to keep this service (..always..) running?
Recursive function, which works with long polling and at first calls in service's onCreate()
(structure):
//"u" is "new utils()".
public class myservice extends Service {
public static boolean started=false;
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "created qweqwe", Toast.LENGTH_LONG).show();
longpoll();
this.started=true;
}
@Override
public void onDestroy() {
super.onDestroy();
this.started=false;
}
private String url = "http://example.com/lp.php";
private void longpoll() {
try {
String resp = u.getData(url); //max time of working u.getData(lpurl) - 25s.
if (resp.length()>0) doSmthWithData(resp); //It works fine
} catch(Exception e) {}
longpoll();
}
}
So, how to keep this service (..always..) running?
Tactically, based on the "15 seconds" in your question title, my guess is that you are doing this long poll on the main application thread. You need to do it on a background thread.
Strategically, you cannot keep a service "always running". You can use startForeground()
to reduce the odds of your service being automatically destroyed, but the user and the OS can still get rid of your process (along with its service) at any time for any reason. Many users do not like services that are "always running" because of the resources they waste, and therefore will attack developers of such services with task killers and low ratings on the Play Store.