Dipak Keshariya
Dipak Keshariya

Reputation: 22291

How to Play Video on OnCreate Method?

How to Play Video on OnCreate Method? I Used Following code for that.But The Video is Not Played.If i used this Code on Click Event of Button then This is Worked.

My OnCreate Method:-

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);      
    getWindow().setFormat(PixelFormat.UNKNOWN);
    surfaceView = (SurfaceView) findViewById(R.id.surfaceview);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setFixedSize(176, 144);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    mediaPlayer = new MediaPlayer();
    mediaPlayer.isLooping();
    playvideo();
}

My PlayVideo Function:-

public void playvideo() {
    String stringPath = "/sdcard/video.mp4";

    if (mediaPlayer.isPlaying()) {
        mediaPlayer.reset();
    }

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setDisplay(surfaceHolder);

    try {
        mediaPlayer.setDataSource(stringPath);
        mediaPlayer.prepare();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    mediaPlayer.start();
}

Thanks in Advance.

Upvotes: 2

Views: 1089

Answers (2)

Zappescu
Zappescu

Reputation: 1439

You cannot play the video calling playvideo() from the onCreate. Put your code in the:

@Override
  public void onWindowFocusChanged(boolean hasFocus) 
  {
      if (hasFocus)
      {
          // play video call
      }
  }

Leave just the declarations in the onCreate.

Upvotes: 2

Shash316
Shash316

Reputation: 2218

You cannot play the video in onCreate, because to play video content you need a surface and Surface has not been created when you had called playVideo().

To get video playback working, you need to do the following

  1. Implement SurfaceHolder callbacks in your activity. Register your class with surfaceholder (surfaceHolder.addCallback(this); )
  2. When the surface is created, surfaceCreated() gets called, where you ll get an instance of surface holder. Now you can call playVideo(with the instance of surfaceHolder). Inside playVideo() get the surface and set it on media player instance.

Shash

Upvotes: 0

Related Questions