Search code examples
androidandroid-videoviewandroid-video-player

Stopping Android video after certain amount of time


I would like to play a video with a VideoView in fullscreen mode in Android 5.1. Moreover, I would like to stop the video (and changing the activity) after a certain amount of time (let's say 5min). How can I achieve that? My layout is the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
   android:id="@+id/LinearLayout01"
   android:layout_height="fill_parent"     
   android:paddingLeft="2px"
   android:paddingRight="2px"
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:paddingTop="2px"
   android:paddingBottom="2px"
   android:layout_width="fill_parent"
   android:orientation="vertical">

      <VideoView 
         android:layout_height="fill_parent"
         android:layout_width="fill_parent" 
         android:id="@+id/VideoView" />

</LinearLayout>

And the following code:

import android.app.Activity;
import android.os.Bundle;
import android.widget.VideoView;

public class VideoViewDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        VideoView videoView = (VideoView)findViewById(R.id.VideoView);

        videoView.setVideoPath("/sdcard/test.mp4");

        videoView.start();  
    }
}

Solution

  • You should use a "MediaPlayer" and then make a "Runnable" to stop the video at 5m. Then with a handler you call your Runnable with ".postDelayed) method like this:

    public class VideoViewDemo extends Activity {
    
            MediaPlayer mp;
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
    
                setContentView(R.layout.main);
    
                mp = MediaPlayer.create(this, "video");  
                mp.start();
    
                Handler handler = new Handler();
                handler.postDelayed(stopPlayerTask, 500000);
            }
    
            Runnable stopPlayerTask = new Runnable(){
                @Override
                public void run() {
                    mp.pause();
                }};
    }
    

    You need to adapt this example ;)