NclsK
NclsK

Reputation: 237

How to measure how long a condition has been true?

I am working on a practice app for musicians. I display a music sheet and cursor(that highlights a note) in a WebView. I already managed to get the cursor to move to the next note when the highlighted note is played. The solution for that is basically to constantly check:

if(payedNote == highlightedNote){
    cursor.next();
}

However, I would like to implement the time component of music into this activity. My thought process was, that the easiest way to achieve this would be to measure how long the note has been played and move the cursor once a set period of time has passed.

My question now is:
Is it possible to check how long this condition has been true and if not, is there a workaround for something like this?

Upvotes: 1

Views: 76

Answers (3)

Farabi Abdelwahed
Farabi Abdelwahed

Reputation: 224

You can use RxAndroid to observe the variable change ,

1- First create the observable and save the start time

  Observable<Boolean> mObservable = Observable.just(payedNote == highlightedNote); 
long startTime = System.currentTimeMillis();

2- Subscribe to the observer

    mObservable.map(new Func1<Boolean, Object>() {

        @Override
        public Object call(Boolean aBoolean) {


            long stopTime = System.currentTimeMillis();
            long elapsedTime = stopTime - startTime;


            Log.d("ELAPSED", String.valueOf(elapsedTime));
            return true;
        }
    });

Finally when the variable changes to false call the mObservable.onNext(false)

 if (payedNote == highlightedNote)
    {
        cursor.next();
    } else {
        mObservavle.onNext(false);
    }

RxAndroid Gradle dependency

implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'io.reactivex.rxjava2:rxjava:2.x.x'

Upvotes: 0

Henrique Andrade
Henrique Andrade

Reputation: 991

Get the current time when the condition changes to true. When it changes to false, get the current time again and calculate the difference

long startTime;
long stopTime;
wasFalse = true

if(payedNote == highlightedNote) {
    cursor.next();
    if (wasFalse) {
        startTime = System.currentTimeMillis();
    }
    wasFalse = false;
} else {
    stopTime = System.currentTimeMillis();
}
System.out.println("Elapsed time was " + (stopTime - startTime) + " miliseconds");

Upvotes: 0

Thorviory
Thorviory

Reputation: 67

You could use a thread, which would essentially run all the time in the background till you tell it to stop, that is the thread would be a listener. So in your thread you would get the time:

  public void start()
    {
        super.start();
        timeStarted = System.currentTimeMillis();
    }

And then when you stop the thread you get the time again, and find the difference between the two.

If you would like to wait for the note to be played you could just use thread.wait()

I hope this helps.

Upvotes: 1

Related Questions