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.
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.
/Sub
ReplyDeleteyou should use AlarmManager to restart the service after 1 up to 3 minutes
ReplyDeleteI 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);
}
}
}
https://forums.embarcadero.com/message.jspa?messageID=863622
ReplyDeleteGenerally, don't sleep at all. It's usually the wrong solution. What is the problem?
ReplyDeleteThank you guys, I will check for the solutions. David, problem is with CPU usage.
ReplyDeleteThat's not a clear specification of the problem. Usually when people sleep they should instead wait until they receive a notification event or message.
ReplyDeleteMy 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.
ReplyDeleteMagno Lima do the location listener need an active application ?
ReplyDeleteI don't think so
stackoverflow.com - design patterns - Android: How to send location information to server while app is inactive - Stack Overflow