What is the best way make my Android Service sleep?

What is the best way make my Android Service sleep?
while Count < FWaitTime do begin
Sleep(1000);
Inc(Count);
end;
Or a unique Sleep(FWaitTime)?

Consider that FWaitTime should wait for some minutes (from 1' up to 3') and meanwhile it has a GPS location update active.
I've noticed that my app is consuming a lot of CPU, sometimes, and sometimes it gets Idle state.

Comments

  1. you should use AlarmManager to restart the service after 1 up to 3 minutes

    I use this in a Android Studio project, don't know how to do the same under Delphi

    public class Receiver extends BroadcastReceiver {
    ...
    static public void Schedule(Context context, int delay) {

    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent alarm = new Intent(context, Receiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarm, PendingIntent.FLAG_UPDATE_CURRENT);

    if (delay < 0) {
    alarmManager.cancel(pendingIntent);
    } else {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MINUTE, delay); // in delay minutes

    alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);

    }
    }
    }

    ReplyDelete
  2. Generally, don't sleep at all. It's usually the wrong solution. What is the problem?

    ReplyDelete
  3. Thank you guys, I will check for the solutions. David, problem is with CPU usage.

    ReplyDelete
  4. That's not a clear specification of the problem. Usually when people sleep they should instead wait until they receive a notification event or message.

    ReplyDelete
  5. My app uses the Location Listener, so if the app "sleeps" and wait for a Alarm Manager maybe I could lost an update from the Location, as it will work "unsynchronized"... I really dont know if it's the best approach.

    ReplyDelete

Post a Comment