I have a service that starts when BOOT_COMPLETED is executed. What I need in that service is to log in to my server but the problem is that the Internet connection is not available yet. I mean, the phone hasn't booted completely. So I have a while() loop with a Sleep() function waiting for the Internet to get connected. The problem is that the Service is killed after 20-30 seconds waiting.
Is that normal? Can't I run forever inside my service?
This is my code:
@Override public void onStart(Intent intent, int startid)
{
for(int i=1; i<=60; i++) //Let's wait 60 seconds for the Internet
{
if(IsInternetConected(MyService.this) == true)
break;
WriteLog("Waiting for internet " + i);
try{Thread.sleep(1000);} catch (InterruptedException e) { };
}
//Here it is connected to Internet or we have been waiting for too long
if(IsInternetConected(MyService.this) == false)
{ WriteLog("Not Internet. Try later");
return;
}
WriteLog("Everything Ok. Continue...");
}
public boolean IsInternetConected(Context Contexto)
{ ConnectivityManager oConnectivityManager = (ConnectivityManager) Contexto.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo oNetworkInfo = oConnectivityManager.getActiveNetworkInfo();
if(oNetworkInfo!=null && oNetworkInfo.isConnected())
return true;
return false;
}
What I see in my log file is:
Waiting for internet 1
Waiting for internet 2
Waiting for internet 3
...
Waiting for internet 28
That's all. It finishes around 20 and 30.