Batzi Batzi - 3 years ago 145
Android Question

How to loop a service?

My service needs to check for something every minute and

while(true)
{
Thread.sleep(60000)
//REST OF CODE HERE//
}


is not working. Making the application freeze and asking me to forcefully stop it.

I am sure the problem is with the while loop but I thought it was the only way to infinitely repeat the service whenever the onStart() method executes.

Any suggestions are appreciated.

EDIT

I fixed it and in case you were wondering how the code looks like well there you go:

@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "Service running", Toast.LENGTH_SHORT).show();

handler = new Handler(){

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Toast.makeText(protectionService.this, "5 secs has passed", Toast.LENGTH_SHORT).show();
}

};



new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
while(true)
{
try {
Thread.sleep(5000);
handler.sendEmptyMessage(0);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
}).start();
}


Basically the service is been called and the tasks of that service will be repeated every 5 secs in that case.

I would like to thank vineetska, Janusz and inazaruk for suggesting to use Handlers. I would like to thank everyone who answered as well, your help was very much appreciated.

Answer Source

create a thread in your service and put while loop there like this:

 new Thread(new Runnable(){
    public void run() {
    // TODO Auto-generated method stub
    while(true)
    {
       Thread.sleep(60000) 
       //REST OF CODE HERE//
    }

                    }
}).start();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download