user3194723
user3194723

Reputation: 25

Android, sleep a service

I'm implementing an app on Android. I've just added a new service that is called on boot-completed. This service creates a new thread that is simply a loop, making something minute after minute. To wait the next minute I used Thread.sleep(60000) but it doesn't work: after the waiting period no other action is performed. It seems that the app is closed or waiting permanentely.

Is there another way to make a loop-service avoiding Thread.sleep? I don't think it is a problem of code because if I call the main method of the service on the app starting it works (it is a problem related to the service)

Thank you in advance

I think the problem is related to the "scan media" of my LG L9 II.. when the "scan media" (I think is about my sd card) is completed all my service are killed (or something like it). Any suggestion?

Upvotes: 2

Views: 4349

Answers (3)

guycole
guycole

Reputation: 808

Consider using AlarmManager to invoke your service. Below example illustrates how to establish repeating events every minute from AlarmManager.

   AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
   Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
   PendingIntent pending = PendingIntent.getBroadcast(getBaseContext(), 0, intent, 0);
   am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), ONE_MINUTE, pending);

Upvotes: 1

Brodo Fraggins
Brodo Fraggins

Reputation: 628

There is almost never a good reason to use Thread.sleep(...) or explicitly create threads in Android. If you need something to happen every 60 seconds, create a Handler and use its postDelayed(...) methods. You can post a task that will re-post itself each time it runs. Just make sure you cancel it when your app is shutting down.

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93559

Services don't have their own thread, the share the main (UI) thread. If you want to do something every minute, create a new thread and have it do something once a minute.

Upvotes: 0

Related Questions