Chapter 8 Notes on Line 2

Keywords: Android xml MediaPlayer Mobile

I haven't updated my blog for a long time, but I've written it, but I haven't published it all the time. I hope I can get more comments from God.

Enriching Your Programs - Using Mobile Multimedia

Running the program on the mobile phone

First connect the phone to the computer through the data line. Then go to the Settings -> Developer Options Interface, where you check the USB debugging options

Note that, starting with Android 4.2, the developer options are hidden by default. You need to enter the "About Mobile" interface first, and then click on the bottom version number column to display the developer options.

Usage notice

Notification is a feature of Android system. When an application wants users to send some prompts, it can be implemented by notification without running in the foreground. After a notification is issued, a notification icon will be displayed in the top status bar of the mobile phone. After dropping down the status bar, you can see the details of the notification.

Basic usage of notification

Notifications can be created either in an activity, in a broadcast receiver, or in a service.

Steps to create notifications

  • First, a Notification Manager is needed to manage the notification, which can be obtained by calling the getSystemService() method of Context. The getSystemService() method receives a string parameter to get which service of the system in Quendong. Here we pass in Context.NOTIFICATION_SERVICE. Therefore, an instance of Notification Manager can be obtained and written as follows:

    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

  • Use the Builder constructor to create Notification objects. A NotificationCompat class is provided in the support-v4 library. The constructor of this class creates Notification objects to ensure that our program works properly on the Android version.

    Notification notification = new NotificationCompat.Builder(context).build();

  • Create a rich Notification object by linking any number of settings before the build() method

    Notification notification = new NotificationCompat.Builder(this)
    .setContentTitle("This is content title")
    .setContentText("This is content text")
    .setWhen(System.currentTimeMillis())
    setSmallIcon(R.mipmap.ic_launcher)// Set notification icons. Note that only alpha layer images can be used for settings. The icons will be displayed on the system status bar.
    SetLargeIcon (BitmapFactory. decodeResource (getResources (), R. mipmap. ic_launcher)// Set the large icon of the system. When you drop down the system status bar, you can see the large icon of the settings.
    .build();

  • Call Notification Manager's notify() method to display the notification. The notify() method receives two parameters, the first parameter id, to ensure that each notification specifies a different ID. The second parameter is the Notification object, which we just created is passed in directly.

    manager.notify(1 , notification);

Create a new physical Notification Test project and modify the code in activity_main.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.demo.notificationtest.MainActivity">

    <Button
        android:id="@+id/send_notice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send notice"
        android:textAllCaps="false"/>
</LinearLayout>

Modify the code in MAinActivity as follows:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendNotice = (Button) findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_notice:
                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                Notification notification = new NotificationCompat.Builder(this)
                        .setContentTitle("This is content title")
                        .setContentText("This is content text")
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources() , R.mipmap.ic_launcher))
                        .build();
                manager.notify(1 , notification);
                break;
            default:
                break;
        }
    }
}

intent tends to execute an action immediately, Pending intent tends to execute an action in a suitable reality.

Create a new Notification Activity with the layout name activity_notification.xml. The code in the layout is as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_notification"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.demo.notificationtest.NotificationActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="24sp"
        android:text="This is notification layout"
        />

</RelativeLayout>

Modify the code in MAinActivity and add a click function to the notification:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendNotice = (Button) findViewById(R.id.send_notice);
        sendNotice.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_notice:
                Intent intent = new Intent(this , NotificationActivity.class);
                PendingIntent pi = PendingIntent.getActivity(this , 0 , intent , 0);

                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                Notification notification = new NotificationCompat.Builder(this)
                        .setContentTitle("This is content title")
                        .setContentText("This is content text")
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources() , R.mipmap.ic_launcher))
                        .setContentIntent(pi)
                        .setAutoCancel(true)//When this notification is clicked, the notification will be cancelled automatically.
                        .build();
                manager.notify(1 , notification);
                break;
            default:
                break;
        }
    }
}

Set mobile phone vibration:
Notification notification = new NotificationCompat.Builder(this)

SetVibrate (new long []{0, 1000, 1000, 1000})// long integer array, used to set the length of the mobile phone's static and vibration in milliseconds. A subscript of 0 indicates the length of the mobile phone at rest, a subscript of 1 indicates the length of the mobile phone's vibration, and a subscript of 2 indicates the length of the mobile phone at rest, and so on.
.build();
If you want to control the vibration of your mobile phone, you have to declare permission:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.notificationtest">

<uses-permission android:name="android.permission.VIBRATE"/>
   ...

</manifest>

The front-end LED lamp of mobile phone can be written as follows:

Notification notification = new NotificationCompat.Builder(this)
...
.setLights(Color.GREEN , 1000 , 1000)//The first parameter is used to specify the color of the LED lamp, the second parameter is used to specify the time when the LED lamp is turned on, in milliseconds, and the third parameter is used to specify the time when I go to the LED lamp, also in milliseconds.
.build();

You can also use the default effect of notification directly. It will decide what ringtone to play and how to vibrate according to the current mobile environment. The following is written:

Notification notification = new NotificationCompat.Builder(this)
...
.setDefaults(NotificationCompat.DEFAULT_ALL)
.build();

Call Camera and Album

Call the camera to take pictures

Application Associated Cache Directory: The location of the SD card used to store the data of the current application village. This directory can be obtained by calling getExternal CacheDir () method. The specific path is / sdcard/Android/data//cache.

Code in activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.demo.camersalbumtest.MainActivity">

    <Button
        android:id="@+id/take_picture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take Photo" />

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

Code in MAinActivity:

public class MainActivity extends AppCompatActivity {

    public static final int TAKE_PHOTO = 1;
    private ImageView picture;
    private Uri imageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button takePhoto = (Button) findViewById(R.id.take_picture);
        picture = (ImageView) findViewById(R.id.picture);
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Create File objects to store photographed pictures
                File outputImage = new File(getExternalCacheDir() , "output_image.jpg");
                try {
                    if (outputImage.exists()){
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (Build.VERSION.SDK_INT >= 24) {
                    imageUri = FileProvider.getUriForFile(MainActivity.this ,
                            "com.demo.camersalbumtest.fileprovider" , outputImage);
                } else {
                    imageUri = Uri.fromFile(outputImage);
                }
                //Start Camera Program
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT , imageUri);
                startActivityForResult(intent , TAKE_PHOTO);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        //Show pictures taken
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }
}

Code in Android Manifest. XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.camersalbumtest">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:authorities="com.demo.camersalbumtest.fileprovider"
            android:name="android.support.v4.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>


    </application>

</manifest>

Right-click the res directory new Directory, create an XML directory, right-click the XML directory New File, create a file_paths.xml file, and then modify the contents of the file_paths.xml file, as follows:

<?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path=""/>
</paths>

Select photos from albums

Modify the code in activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.demo.camersalbumtest.MainActivity">

    <Button
        android:id="@+id/take_picture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Take Photo"
        android:textAllCaps="false"/>

    <Button
        android:id="@+id/choose_from_album"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choose From Album"
        android:textAllCaps="false"/>

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

Code in MAinActivity:

public class MainActivity extends AppCompatActivity {

    public static final int TAKE_PHOTO = 1;
    private ImageView picture;
    private Uri imageUri;
    private static final int CHOOSE_PHOTO = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button takePhoto = (Button) findViewById(R.id.take_picture);
        Button chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);
        picture = (ImageView) findViewById(R.id.picture);

        chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(MainActivity.this ,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(MainActivity.this , new
                    String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE} , 1);
                } else {
                    openAlbum();
                }
            }
        });
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Create File objects to store photographed pictures
                File outputImage = new File(getExternalCacheDir() , "output_image.jpg");
                try {
                    if (outputImage.exists()){
                        outputImage.delete();
                    }
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (Build.VERSION.SDK_INT >= 24) {
                    imageUri = FileProvider.getUriForFile(MainActivity.this ,
                            "com.demo.camersalbumtest.fileprovider" , outputImage);
                } else {
                    imageUri = Uri.fromFile(outputImage);
                }
                //Start Camera Program
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT , imageUri);
                startActivityForResult(intent , TAKE_PHOTO);
            }
        });
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent , CHOOSE_PHOTO);//Open Album
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                } else {
                    Toast.makeText(this , "You denied the permission" , Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        //Show pictures taken
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;

            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    //Judging the Version Number of Mobile Phone System
                    if (Build.VERSION.SDK_INT >= 19) {
                        //4.4 and above systems use this method to process files
                        handleImageOnKitKat(data);
                    } else {
                        //4.4 and below systems use this method to process pictures
                        handleImageBeforeKitKat(data);
                    }
                }
            default:
                break;
        }
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri , null);
        displayImage(imagePath);
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this , "failed to get image" , Toast.LENGTH_SHORT).show();
        }
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //Get the real image path through Uri and selection
        Cursor cursor = getContentResolver().query(uri , null , selection , null , null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this , uri)) {
            //If it is a document type uri, it is handled by document id
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];//Resolve the id of the digital format
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads") ,
                        Long.valueOf(docId));
                imagePath = getImagePath(contentUri , null);
            } else if ("content".equalsIgnoreCase(uri.getScheme())){
                //If it's a uri of content type, it's handled in a normal way
                imagePath = getImagePath(uri , null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                //If it is a file-type uri, you can get the image path directly.
                imagePath = uri.getPath();
            }
            displayImage(imagePath);//Display pictures according to their path
        }
    }
}

Android system started with version 4.4. Pictures in the album are no longer returned to the real Uri of the picture, but a packaged Uri. Therefore, if you are a mobile phone with version 4.4 or more, you need to parse the Uri.

Some photos are still very large even after being clipped, and loading them directly into memory may cause the program to crash. A better way is to compress the photos appropriately according to the requirements of the project and then load them into memory.

Playing Multimedia Files

Create a new PlayAutoTest project and modify the code in activity_main.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.demo.playaudiotest.MainActivity">

    <Button
        android:id="@+id/play"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="play"
        android:textAllCaps="false" />

    <Button
        android:id="@+id/pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="pause"
        android:textAllCaps="false" />

    <Button
        android:id="@+id/stop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="stop"
        android:textAllCaps="false" />
</LinearLayout>

The code in MAinActivity is as follows:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private MediaPlayer mediaPlayer = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button play = (Button) findViewById(R.id.play);
        Button pause = (Button) findViewById(R.id.pause);
        Button stop = (Button) findViewById(R.id.stop);

        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        stop.setOnClickListener(this);

        if (ContextCompat.checkSelfPermission(MainActivity.this , Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this , new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE} , 1);
        } else {
            initMediaPlayer();//Initialize MediaPlayer
        }
    }

    private void initMediaPlayer() {
        try {
            File file = new File(Environment.getExternalStorageDirectory() , "music.mp3");
            mediaPlayer.setDataSource(file.getPath());//Specify the path of the audio file
            mediaPlayer.prepare();//Get MediaPlayer ready
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initMediaPlayer();
                } else {
                    Toast.makeText(this , "Rejecting permissions will not allow the program to be used" , Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.play:
                if ((!mediaPlayer.isPlaying())){
                    mediaPlayer.start();//Start playing
                }
                break;
            case R.id.pause:
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.pause();//Pause playback
                }
                break;
            case R.id.stop:
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.reset();//stop playing
                    initMediaPlayer();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null ){
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}

Add permissions in AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Play video

The VideoView class is mainly used to achieve this. This class integrates the display and control of video into one. With this class, we can complete a suggested video player.

Create a new PlayVideoTest project and modify the code in activity_main.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/play"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Play" />

        <Button
            android:id="@+id/pause"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Pause" />

        <Button
            android:id="@+id/replay"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Replay" />

    </LinearLayout>

    <VideoView
        android:id="@+id/video_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

The code in MAinActivity is as follows:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private VideoView videoView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        videoView = (VideoView) findViewById(R.id.video_view);
        Button play = (Button) findViewById(R.id.play);
        Button pause = (Button) findViewById(R.id.pause);
        Button replay = (Button) findViewById(R.id.replay);
        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        replay.setOnClickListener(this);
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            initVideoPath(); // Initialize MediaPlayer
        }
    }

    private void initVideoPath() {
        File file = new File(Environment.getExternalStorageDirectory(), "movie.mp4");
        videoView.setVideoPath(file.getPath()); // Specify the path of the video file
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initVideoPath();
                } else {
                    Toast.makeText(this, "Rejecting permissions will not allow the program to be used", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                if (!videoView.isPlaying()) {
                    videoView.start(); // Start playing
                }
                break;
            case R.id.pause:
                if (videoView.isPlaying()) {
                    videoView.pause(); // Pause playback
                }
                break;
            case R.id.replay:
                if (videoView.isPlaying()) {
                    videoView.resume(); // Replay
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (videoView != null) {
            videoView.suspend();
        }
    }
}

Note: VideoView is not a versatile video playback tool class. It has some shortcomings in video format support and playback efficiency. So it's not realistic to write a very powerful video player just using ideoView.

Posted by fnairb on Thu, 04 Apr 2019 15:57:31 -0700