Search code examples
androidtimergpshandlerrunnable

unable to place handler and runnable inside OnLocationChanged()


I have calculated the speed of vehicle and comparing that speed with certain threshold value i.e. speed<=3 , Now the problem is to calculate the waiting time. i am trying to calculate waiting time for vehicle if car stays more than two minutes than that overall time after waiting more than two minutes will be added to waiting time .. i used handler and runnable inside onLocationchanged() but my time calculation is random . different handlers and runnable are running at a time and time is faster than the defined one.

@Override
public void onLocationChanged(Location location) {
    diaplayViews();


    timeGpsUpdate = location.getTime();
    float delta = (timeGpsUpdate - timeOld) / 1000;


    if (location.getAccuracy() <100) {

        distance += locationOld.distanceTo(location);


        Log.e("location:", location + "");




        speed = (long) (distance / delta);


        if(speed<=3)

        {
            if(runable==null)
            {


             runnable = new Runnable() {

                public void run() {
                    waitingTime++;
                    updateHandler.postDelayed(this, 10000); // determines the execution interval waiting time addition on every 10 seconds after 2 minutes initially

                }

            };}

            updateHandler.postDelayed(runnable, 60*2*1000); // acts like the initial delay
        }
        else {
            handler.removeCallbacks(runable);

            runable=null;
        }

        locationOld = location;
        timeOld = timeGpsUpdate;
        diaplayViews();

    }

}

Solution

  • use if(location.getspeed()==0.0) and run handler on every 10 seconds and add two minutes(2*60) initially and for other time keep on adding that time i.e. 10 seconds and finally divide it by 60. you will get The best way is use Services which will run the programm in the background and use broadcastreceiver to notify the user or to display the results in the UI.. http://developer.android.com/guide/components/services.html and for broadcast receiver http://developer.android.com/reference/android/content/BroadcastReceiver.html