Search code examples
javaandroidandroid-videoviewandroid-handler

Android Studio- Trouble with setting activity start delay


This is my first question so sorry if I don't provide all the needed info. Just comment and I'll add it.

Onto the problem itself. I'm trying to make a splash screeen of sorts which consists of a short video. I want the app to start the following activity after the video ends, but after I start the app it just starts the second activity right away (Menu.class in the code). Once I'm in the Menu activity I can go back but all i see is a black VideoView. Also, the VideoView worked before I added the Handler. Not sure if it even could have been the problem (new to android studio) but doesn't work even after removing @Override (probably a stupidity, right?). Or can it be caused by the Menu.java activity? (It's just the standard pre-generated preset, I didn't make any changes to it)

public class splash_screen extends AppCompatActivity {
static long duration;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_ACTION_BAR);
    setContentView(R.layout.activity_splash_screen);

    VideoView videoView = this.findViewById(R.id.videoView);
    String path = "android.resource://" + getPackageName() + "/" + R.raw.splash;
    videoView.setVideoURI(Uri.parse(path));
    videoView.start();

    duration = videoView.getDuration();
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            startActivity(new Intent(splash_screen.this, Menu.class));
        }
    }, duration);
}
}

Thanks for any and every advice, and like I said let me know if you need more info on the problem.


Solution

  • VideoView need some time to warm up, so here:

    videoView.start();
    duration = videoView.getDuration();
    

    duration could be 0, that is why handler fires immediately. To switch to the second activity you should remove handler part and use:

    videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
         @Override
         public void onCompletion(MediaPlayer mediaPlayer) {
               startActivity(new Intent(splash_screen.this, Menu.class));
               finish();//close activity
         }
    });