Services or intent services to send location updates every 5 sec to server endlessly?

If you want to achieve this using service

    public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) 
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
        // This schedule a runnable task every x unit of time
        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() 
        {
            public void run() 
            {
                callAPI();
            }
        }, 0, 10, TimeUnit.SECONDS);
        return START_STICKY;
    }

    @Override
    public void onDestroy() 
    {
        super.onDestroy();
    }

    public void callAPI() 
    {
    //Upload data to server and do your stuff
    }
}

Also you need to register your service in AndroidManifest.xml

<service
        android:name=".service.MyService"
        android:enabled="true"
        android:exported="true"
        android:stopWithTask="false" />

And call your service through Activity

if (!checkServiceRunning()) 
    {
        Intent intent = new Intent(MainActivity.this, MyService.class);
        startService(intent);
    }

Leave a Comment