Handler.postDelayed(...) does not delay the Runnable

Flo picture Flo · Aug 26, 2013 · Viewed 12.8k times · Source

i've implemented an OnCompletionListener by myself which looks like this:

public class SongEndCompletionListener  implements OnCompletionListener{

    String nextView;
    Context actualActivity;
    int stopTime;

    public SongEndCompletionListener(Context activity, String nextView, int time) {
        this.nextView = nextView;
        actualActivity = activity;
    }
    @Override
    public void onCompletion(MediaPlayer arg0) {


            Handler handler = new Handler(); 
            handler.postDelayed(new Runnable() { 
                 public void run() { 
                        try {
                     Intent stopplay;
                     stopplay = new Intent(actualActivity,Class.forName(nextView));
                     actualActivity.startActivity(stopplay);    
                 } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    } 
                 } 
            }, stopTime); 


    }
}

I want it to pause for stopTime seconds, but what it actually does is as soon as the audiofile ends it jumps to the next view. Could you maybe point me towards where i am wrong or how i could delay the switch to another Activity differently?

Every hint is appreciated!

Answer

Philipp Jahoda picture Philipp Jahoda · Aug 26, 2013

I know why your Handler does not post delayed.

It is because your stopTime is 0.

You need to set a value for "stopTime", otherwise it will be 0. For example to delay the Runnable for one second:

stopTime = 1000; // milliseconds

Or use your Constructor:

public SongEndCompletionListener(Context activity, String nextView, int time) {
    this.nextView = nextView;
    actualActivity = activity;
    this.stopTime = time; // you forgot this
}