whiteLT
whiteLT

Reputation: 338

calculate elapsed time(second time mark - first time mark)

I have service(Service has a Broadcast receiver, that listens for ACTION_BATTERY_CHANGED), that I want to calculate time passed between two time marks, this what I have:

public void onReceive(Context context, Intent intent){
                    int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                long time;
                long startTime=0;

                    if(OldLevel==0){
                    OldLevel=level;
                    startTime = System.nanoTime();

                    }
                    else{

                        time=System.nanoTime()-startTime;
                        startTime=System.nanoTime();  //edited


                    Log.e("inFFFF","FFFF "+time);// I somehow here get 16243428223995 nanoseconds which are too large because in reality it just take 1-2min.
                    }

                }

If you are able please: 1. Tell me why time is larger than expected 2. Or suggest better way to calculate time that is being elapsed.

Upvotes: 1

Views: 4145

Answers (2)

Pragnani
Pragnani

Reputation: 20155

At the time of else start time is always zero. so you need to capture the start time in the beginning it self.

i.e

long startTime=System.nanoTime();

otherwise keep the remaining code as it is

Upvotes: 1

omer schleifer
omer schleifer

Reputation: 3935

In your code example you assign startTime with a value, only if condition 1 is met. (else you calculate System.nanoTime()-startTime where startTime is 0)

So in fact you are comparing now time to 0 which is the initial value of start time. this is wrong. nano time is used to measure elapsed time. you should always compare System.nanoTime() to other calls of System.nanoTime(). see: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#nanoTime()

maybe try something like this :

public void onReceive(Context context, Intent intent){

                long time;
                long startTime= System.nanoTime();

                    if(....){

                    startTime = System.nanoTime();

                    }
                    else{

                        time=System.nanoTime()-startTime;



                    Log.e("inFFFF","FFFF "+time);// I somehow here get 16243428223995 nanoseconds which are too large because in reality it just take 1-2min.
                    }

                }

Upvotes: 3

Related Questions