Skip to content
Advertisement

How to pause the current loop without pausing current running thread in Android / Java?

In my android application, In my fragment, I have one while loop like

startMs=0, endMs=30000;
while(i<10){
    new Mp4Composer(inputPath, destPath)
                                .trim(startMs, endMs)
                                .listener(new Mp4Composer.Listener() {
                                   @Overide
                                     public void onCompleted(){

                                        }
                                   }
                                .start();
startMs= endMs;
endMs+=30000;
i++
}

Here new Mp4Composer is a Thread… This task is executed for each iteration of the loop..without completing the previous task (on task still in processing state)… the loop jumped to the next iteration.so the existing task doesn’t produce any output… and jumped to next task because of the loop.

So here what I want is while loop should wait to complete new Mp4Composer each task. By using public void onCompleted() method… we able to identify when that async task will finish for each task.

And here I should not pause the current running thread (where the class while loop running). The reason is when I pause while loop placed class thread, the total UI, and my android application gets paused. I haven’t much knowledge about Thread.

Advertisement

Answer

Handler mHandler = new Handler();
int startMs=0, endMs=30000, i=0;
Runnable action = new Runnable(){
    @Override
    public void run() {
        new Mp4Composer(inputPath, destPath)
                .trim(startMs, endMs)
                .listener(new Mp4Composer.Listener() {
                    @Overide
                    public void onCompleted(){
                        goNext();
                    }
                }
                .start();
    }
};
void goNext(){
    if(i < 10) {
        startMs = endMs;
        endMs += 30000;
        i++;
        mHandler.postDelayed(action, 2000); //2 second
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement