Steven Pongidin
Steven Pongidin

Reputation: 153

Android Thread stop randomly in the middle of process

As the question says, here's the code.

What I want to do basically is I have a list of array, says "myArray". This array contains stored time points in millisecond. Next thing is I want to call a method based on those time points. So, I need to run a time counter from 0 while the music is playing, compare the time counter with the time points in the array progressively (from first array index until finished).

The first method "timeCounter" is a method to start a time counter while a music is playing through MediaPlayer.

public void timeCounter(){
    Runnable myRunnable = new Runnable(){
        @Override
        public void run(){
            while(musicPlaying){
                startCounter(arrayPos);
            }
        }
    };
    Thread musicPlayer = new Thread(myRunnable);
    musicPlayer.start();
}

This is where the comparison of time counter and time in the array takes place.

public void startCounter(List<Long> array){
    elapsedTime = System.currentTimeMillis() - timeStart;
    if(elapsedTime == array.get(arrayPos)){
        arrayPos += 1;  //Continue comparing with the next number in the array
        Log.v("DEBUG", "TIME MATCHES!");
        if(arrayPos>= array.size()){
            arrayPos= 0;  //Prevent out of array index
        }
    }
}

I have the code running correctly and the result from the LogCat is correct.

Now the problem is sometimes the Thread is not running until the music finished playing (I have set onCompletionListener and set "musicPlaying" to false when music finished). The stopping point is totally random, sometimes when it's just started, or around 50%, or even when it's near to completion. Sometimes it doesn't even start! I've been trying to figure out why but I couldn't find any info about Thread stopping halfway or such in anywhere. Thanks in advance! =)

Upvotes: 1

Views: 438

Answers (2)

OldCurmudgeon
OldCurmudgeon

Reputation: 65859

I suspect your if(elapsedTime == array.get(arrayPos)) should be if(elapsedTime >= array.get(arrayPos)).

You need to remember that the millisecond timer does not necessarily have a one millisecond tick. On Windows, for example, the returned value will only change every 15 ms or so. You may therefore completely miss a particular time and therefore never get past that entry in your list.

Upvotes: 1

Tudor
Tudor

Reputation: 62459

If musicPlaying is modified and read between threads, make sure it is declared volatile.

Upvotes: 2

Related Questions