2

After a long search I'm still confused about it although I found some related posts but they were not answering what I was looking for. in my scenario I want to send user's lat long at fixed intervals like every 5 minutes to a server. to do this I used a service with its own process so that it doesn't get killed when Activity destroyed and in service method onStartCommand I used a while loop having condition of always true and in that loop I update location to server and give delay by thread.sleep like shown below

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
   While(true)
           {
            Location currentLocation = getLocation();
            updateLocationToServer(currentLocation);
            try
               {
                Thread.sleep(300000)
               }
            catch(Exception e)
               {
                e.printStackTrace()
               }
           }
return Service.START_STICKY;

here I cannot understand the return statement is unreachable then how can the service will be restarted automatically when it is destroyed and secondly using thread.sleep causing ANR (Application Not Responding) while service is a background process and I found that its directly running in UI thread these information are confusing me and in this case what is the best way to get desired functionality.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Umar Qureshi
  • 5,985
  • 2
  • 30
  • 40

3 Answers3

3

You should use and AlertManager instead!

AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);

mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);

http://justcallmebrian.com/?p=129

Thkru
  • 4,218
  • 2
  • 18
  • 37
1
secondly using thread.sleep causing ANR (Application Not Responding) while service is a background process

from http://developer.android.com/reference/android/app/Service.html

Note that services, like other application objects, run in the main thread of their hosting process.

Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
0

Try using Alarm Manager instead, see this example of how to set it to repeat every 5 minutes

Community
  • 1
  • 1
MrEngineer13
  • 38,642
  • 13
  • 74
  • 93