Advertisement
mmayoub

MainActivity.java (Video View Example)

Jul 11th, 2023
921
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.07 KB | Software | 0 0
  1. package com.example.myvideoviewplayer;
  2.  
  3. import androidx.appcompat.app.AppCompatActivity;
  4.  
  5. import android.net.Uri;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.VideoView;
  10.  
  11. public class MainActivity extends AppCompatActivity {
  12.     private VideoView mVideoView;
  13.     private Button btnPlay, btnStop;
  14.     private Uri videoUri;
  15.  
  16.     @Override
  17.     protected void onCreate(Bundle savedInstanceState) {
  18.         super.onCreate(savedInstanceState);
  19.         setContentView(R.layout.activity_main);
  20.  
  21.  
  22.         mVideoView = findViewById(R.id.vvVideoView);
  23.         btnPlay = findViewById(R.id.btnPlay);
  24.         btnStop = findViewById(R.id.btnStop);
  25.  
  26.         initializeVideo();
  27.  
  28.         btnPlay.setOnClickListener(new View.OnClickListener() {
  29.             @Override
  30.             public void onClick(View v) {
  31.                 startVideo();
  32.             }
  33.         });
  34.  
  35.         btnStop.setOnClickListener(new View.OnClickListener() {
  36.             @Override
  37.             public void onClick(View v) {
  38.                 stopVideo();
  39.             }
  40.         });
  41.     }
  42.  
  43.     private void initializeVideo() {
  44.         String mediaName = "video_file_example"; // file name from raw folder
  45.         String uriString = "android.resource://" + getPackageName() + "/raw/" + mediaName;
  46.         videoUri = Uri.parse(uriString);
  47.         mVideoView.setVideoURI(videoUri);
  48.     }
  49.  
  50.     private void startVideo() {
  51.         if (!mVideoView.isPlaying()) {
  52.             mVideoView.setVideoURI(videoUri);
  53.             mVideoView.start();
  54.             btnPlay.setEnabled(false);
  55.             btnStop.setEnabled(true);
  56.         }
  57.     }
  58.  
  59.     private void stopVideo() {
  60.         if (mVideoView.isPlaying()) {
  61.             mVideoView.stopPlayback();
  62.             btnPlay.setEnabled(true);
  63.             btnStop.setEnabled(false);
  64.         }
  65.     }
  66.  
  67.  
  68.     @Override
  69.     protected void onPause() {
  70.         stopVideo();
  71.         super.onPause();
  72.     }
  73.  
  74.     @Override
  75.     protected void onResume() {
  76.         super.onResume();
  77.         startVideo();
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement