Ton
Ton

Reputation: 9736

Service killed when starting

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.

Upvotes: 0

Views: 50

Answers (2)

PedroHawk
PedroHawk

Reputation: 630

If you perform any code which block your UI, your service is killed after X seconds, thats standard.

You should perform an AsyncTask, and put that code inside on doInBackground. This step is used to perform background computation that can take a long time.

Upvotes: 0

jush
jush

Reputation: 633

Yes, it's normal. See Service documentation where it says:

[...] if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.

Maybe you can use IntentService.

Upvotes: 1

Related Questions