Skip to content Skip to sidebar Skip to footer

Services Or Intent Services To Send Location Updates Every 5 Sec To Server Endlessly?

I am using GoogleCientApi object to fetch location updates and other Accelerometer sensors and send it to server every 5 sec . I want it to run in background endlessly i.e. 24*7 wi

Solution 1:

If you want to achieve this using service

publicclassMyServiceextendsService {
    @Nullable@Overridepublic IBinder onBind(Intent intent) 
    {
        returnnull;
    }

    @OverridepublicintonStartCommand(Intent intent, int flags, int startId)
    {
        ScheduledExecutorServicescheduleTaskExecutor= Executors.newScheduledThreadPool(5);
        // This schedule a runnable task every x unit of time
        scheduleTaskExecutor.scheduleAtFixedRate(newRunnable() 
        {
            publicvoidrun() 
            {
                callAPI();
            }
        }, 0, 10, TimeUnit.SECONDS);
        return START_STICKY;
    }

    @OverridepublicvoidonDestroy() 
    {
        super.onDestroy();
    }

    publicvoidcallAPI() 
    {
    //Upload data to server and do your stuff
    }
}

Also you need to register your service in AndroidManifest.xml

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

And call your service through Activity

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

Solution 2:

This is posible with use of following component

Use Android Foreground Service for get current location while app open / close.

Note: Latest Android versions is not allowing to get current location through Backghround service.

Use Socket/Pusher for update location to user server.

Reference link

1). https://developer.android.com/guide/components/services.html

2). http://www.truiton.com/2014/10/android-foreground-service-example/

For Socket

1). https://socket.io/blog/native-socket-io-and-android/

2). https://github.com/socketio/socket.io-client-java

For Pusher

1). https://pusher.com/docs/android_quick_start

Post a Comment for "Services Or Intent Services To Send Location Updates Every 5 Sec To Server Endlessly?"