Tracking time spent at a location in Android using Google apis

671 Views Asked by At

I need to track the time spent by the app user at a particular location. Please suggest me an optimized approach. I looked into this link.

I can use the above for getting the location, but what should my approach to achieve what I want ?

1

There are 1 best solutions below

0
Dhruv Patel On

The main idea is to fetch current user location at defined interval and if location goes beyond your region, we can calculate time difference

Follow this steps

 long time1 = new Date().getTime();
 long time2;

 double firstLat, firstLog;
 // fetch current user location using this link
 // https://developer.android.com/training/location/retrieve-current.html

 //Declare the timer
 Timer timer = new Timer();
 //Set the schedule function and rate
 timer.scheduleAtFixedRate(new TimerTask() {

      @Override
      public void run() {
         // Called each time when 1000 milliseconds (1 second) (the period parameter)

         double curLat, curLog;

         // fetch current user location using this link
         // https://developer.android.com/training/location/retrieve-current.html

         if(!isUserInRegion(firstLat,firstLog,curLat,curLog){
             time2 = new Date().getTime();
             timer.cancel();
             timer.purge();
      }

 },
 //Set how long before to start calling the TimerTask (in milliseconds)
 0,
 //Set the amount of time between each execution (in milliseconds)
 1000);
 long timeDiff = time2 - time1;


 private boolean isUserInRegion(double firstLat, double firstLog, double curLat, double curLog){
      int r = 0.005; // Any radious
      double dx = curLat - firstLat;
      double dy = curLog - firstLog;
      return dx * dx + dy * dy <= r * r;
 }

Hope so this trick works for you :)