Tuesday, October 8, 2019

fingerprint lock

main fest

<uses-permission android:name="android.permission.USE_FINGERPRINT" />
activity main xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="START AUTHENTICATION" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
The code for the dialog_fingerprint.xml is given below:
 <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="24dp" android:paddingTop="24dp" android:paddingRight="24dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent"> <TextView android:id="@+id/titleTextView" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Fingerprint Dialog" android:textAppearance="?android:attr/textAppearanceLarge" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" /> <TextView android:id="@+id/subtitleTextView" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Confirm fingerprint to continue." app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/titleTextView" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="28dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@id/subtitleTextView" app:srcCompat="@drawable/ic_fingerprint_white_24dp" /> <TextView android:id="@+id/errorTextView" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginStart="16dp" android:gravity="center_vertical" android:text="Touch sensor" app:layout_constraintBottom_toBottomOf="@id/fab" app:layout_constraintLeft_toRightOf="@id/fab" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="@id/fab" /> <LinearLayout android:id="@+id/buttons" style="?android:attr/buttonBarStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:gravity="end" android:orientation="horizontal" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/fab"> <Button android:id="@+id/btnCancel" style="?android:attr/buttonBarButtonStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" /> </LinearLayout> </android.support.constraint.ConstraintLayout>
FingerprintHelper.java
 package com.journaldev.androidfingerprintapi; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.hardware.fingerprint.FingerprintManager; import android.os.CancellationSignal; import android.support.v4.app.ActivityCompat; public class FingerprintHelper extends FingerprintManager.AuthenticationCallback { private Context mContext; private FingerprintManager mFingerprintManager; private CancellationSignal mCancellationSignal; private Callback mCallback; public FingerprintHelper(FingerprintManager fingerprintManager, Context context, Callback callback) { mContext = context; mFingerprintManager = fingerprintManager; mCallback = callback; } public boolean isFingerprintAuthAvailable() { return mFingerprintManager.isHardwareDetected() && mFingerprintManager.hasEnrolledFingerprints(); } public void startAuthentication(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) { if (!isFingerprintAuthAvailable()) return; mCancellationSignal = new CancellationSignal(); if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) { return; } manager.authenticate(cryptoObject, mCancellationSignal, 0, this, null); } public void stopListening() { if (mCancellationSignal != null) { mCancellationSignal.cancel(); mCancellationSignal = null; } } @Override public void onAuthenticationError(int errMsgId, CharSequence errString) { mCallback.onError(errString.toString()); } @Override public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) { mCallback.onHelp(helpString.toString()); } @Override public void onAuthenticationFailed() { mCallback.onAuthenticated(false); } @Override public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { mCallback.onAuthenticated(true); } public interface Callback { void onAuthenticated(boolean b); void onError(String s); void onHelp(String s); } }
manager.authenticate(cryptoObject, mCancellationSignal, 0, this, null);
MainActivity.java 
 package com.journaldev.androidfingerprintapi; import android.support.v4.hardware.fingerprint.FingerprintManagerCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button button; FingerprintManagerCompat managerCompat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); button.setOnClickListener(this); } private void showFingerPrintDialog() { FingerprintDialog fragment = new FingerprintDialog(); fragment.setContext(this); fragment.show(getSupportFragmentManager(), ""); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: managerCompat = FingerprintManagerCompat.from(MainActivity.this); if (managerCompat.isHardwareDetected() && managerCompat.hasEnrolledFingerprints()) { showFingerPrintDialog(); } else { Toast.makeText(getApplicationContext(), "Fingerprint not supported", Toast.LENGTH_SHORT).show(); } break; } } }
FingerprintDialog.java
 package com.journaldev.androidfingerprintapi; import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; import android.hardware.fingerprint.FingerprintManager; import android.os.Bundle; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyPermanentlyInvalidatedException; import android.security.keystore.KeyProperties; import android.support.v4.app.DialogFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; public class FingerprintDialog extends DialogFragment implements FingerprintHelper.Callback { Button mCancelButton; public static final String DEFAULT_KEY_NAME = "default_key"; FingerprintManager mFingerprintManager; private FingerprintManager.CryptoObject mCryptoObject; private FingerprintHelper mFingerprintHelper; KeyStore mKeyStore = null; KeyGenerator mKeyGenerator = null; KeyguardManager mKeyguardManager; private Context mContext; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Material_Light_Dialog); try { mKeyStore = KeyStore.getInstance("AndroidKeyStore"); } catch (KeyStoreException e) { e.printStackTrace(); } try { mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } Cipher defaultCipher; try { defaultCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new RuntimeException("Failed to get an instance of Cipher", e); } mKeyguardManager = getContext().getSystemService(KeyguardManager.class); mFingerprintManager = getContext().getSystemService(FingerprintManager.class); mFingerprintHelper = new FingerprintHelper(mFingerprintManager, getContext(), this); if (!mKeyguardManager.isKeyguardSecure()) { Toast.makeText(getContext(), "Lock screen not set up.\n" + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint", Toast.LENGTH_LONG).show(); return; } createKey(DEFAULT_KEY_NAME); if (initCipher(defaultCipher, DEFAULT_KEY_NAME)) { mCryptoObject = new FingerprintManager.CryptoObject(defaultCipher); } } private boolean initCipher(Cipher cipher, String keyName) { try { mKeyStore.load(null); SecretKey key = (SecretKey) mKeyStore.getKey(keyName, null); cipher.init(Cipher.ENCRYPT_MODE, key); return true; } catch (KeyPermanentlyInvalidatedException e) { Toast.makeText(mContext, "Keys are invalidated after created. Retry the purchase\n" + e.getMessage(), Toast.LENGTH_LONG).show(); return false; } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) { Toast.makeText(mContext, "Failed to init cipher", Toast.LENGTH_LONG).show(); return false; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.dialog_fingerprint, container, false); mCancelButton = v.findViewById(R.id.btnCancel); mCancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dismiss(); } }); return v; } @Override public void onResume() { super.onResume(); if (mCryptoObject != null) { mFingerprintHelper.startAuthentication(mFingerprintManager, mCryptoObject); } } @Override public void onPause() { super.onPause(); mFingerprintHelper.stopListening(); } public void setContext(Context context) { mContext = context; } public void createKey(String keyName) { try { mKeyStore.load(null); KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keyName, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7); mKeyGenerator.init(builder.build()); mKeyGenerator.generateKey(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException | IOException e) { throw new RuntimeException(e); } } @Override public void onAuthenticated(boolean b) { if (b) { Toast.makeText(mContext.getApplicationContext(), "Auth success", Toast.LENGTH_LONG).show(); dismiss(); } else Toast.makeText(mContext.getApplicationContext(), "Auth failed", Toast.LENGTH_LONG).show(); } @Override public void onError(String s) { Toast.makeText(mContext.getApplicationContext(), s, Toast.LENGTH_LONG).show(); } @Override public void onHelp(String s) { Toast.makeText(mContext.getApplicationContext(), "Auth help message:" + s, Toast.LENGTH_LONG).show(); } }

Sunday, September 29, 2019

upload images code

main java


package com.google.top.my;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    Button chooseImg, uploadImg;
    ImageView imgView;
    int PICK_IMAGE_REQUEST = 111;
    Uri filePath;
    ProgressDialog pd;

    //creating reference to firebase storage    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("gs://wallpaper-app-1b2cd.appspot.com");    //change the url according to your firebase app

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        chooseImg = (Button)findViewById(R.id.chooseImg);
        uploadImg = (Button)findViewById(R.id.uploadImg);
        imgView = (ImageView)findViewById(R.id.imgView);

        pd = new ProgressDialog(this);
        pd.setMessage("Uploading....");


        chooseImg.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
            }
        });

        uploadImg.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                if(filePath != null) {
                    pd.show();
                    String imageID = UUID.randomUUID().toString();
                    StorageReference childRef = storageRef.child(imageID);

                    //uploading the image                    UploadTask uploadTask = childRef.putFile(filePath);

                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                           @Override                             public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            pd.dismiss();
                            Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
                        }
                    });

                     uploadTask.addOnFailureListener(new OnFailureListener() {
                        @Override                        public void onFailure(@NonNull Exception e) {
                            pd.dismiss();
                            Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                else {
                    Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

                       @Override                  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                 super.onActivityResult(requestCode, resultCode, data);

                   if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                      filePath = data.getData();

                      try {
                //getting image from gallery                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);

                //Setting image to ImageView                         imgView.setImageBitmap(bitmap);
                        } catch (Exception e) {
                         e.printStackTrace();
                   }
        }
    }
}






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


    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Choose Image"        android:id="@+id/chooseImg"/>

    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Upload Image"        android:id="@+id/uploadImg"/>

    <ImageView        android:layout_width="match_parent"        android:layout_height="300dp"        android:id="@+id/imgView"/>


</LinearLayout>




appp


implementation 'com.google.firebase:firebase-storage:16.0.4'implementation 'com.google.firebase:firebase-auth:16.0.5'
apply plugin: 'com.google.gms.google-services'




classpath 'com.google.gms:google-services:4.2.0'

Friday, September 20, 2019

video player

main activity .java



package com.google.earnshayro.myplyer;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    private EditText videoPathEditor = null;

    private Button browseVideoFileButton = null;

    private Button playVideoButton = null;

    private Button stopVideoButton = null;

    private Button pauseVideoButton = null;

    private Button continueVideoButton = null;

    private Button replayVideoButton = null;

    private VideoView playVideoView = null;

    private ProgressBar videoProgressBar = null;

    // Request code for user select video file.    private static final int REQUEST_CODE_SELECT_VIDEO_FILE = 1;

    // Request code for require android READ_EXTERNAL_PERMISSION.    private static final int REQUEST_CODE_READ_EXTERNAL_PERMISSION = 2;

    // Used when update video progress thread send message to progress bar handler.    private static final int UPDATE_VIDEO_PROGRESS_BAR = 3;

    // Save local video file uri.    private Uri videoFileUri = null;

    // Wait update video progress thread sent message, then update video play progress.    private Handler videoProgressHandler = null;

    // Save current video play position.    private int currVideoPosition = 0;

    // Save whether the video is paused or not.    private boolean isVideoPaused = false;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Init this example used video components.        initVideoControls();

        // When user input video file url in the video file path edittext input text box.        videoPathEditor.setOnKeyListener(new View.OnKeyListener() {
            @Override            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                int action = keyEvent.getAction();
                if(action == KeyEvent.ACTION_UP) {
                    String text = videoPathEditor.getText().toString();
                    if (text.length() > 0) {
                        // If user input video file url, enable play button.                        playVideoButton.setEnabled(true);
                        pauseVideoButton.setEnabled(false);
                        replayVideoButton.setEnabled(false);
                    } else {
                        // If user input nothing, disable all buttons.                        playVideoButton.setEnabled(false);
                        pauseVideoButton.setEnabled(false);
                        replayVideoButton.setEnabled(false);
                    }
                }
                return false;
            }
        });

        // If user click browse video file button.        browseVideoFileButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                // Check whether user has granted read external storage permission to this activity.                int readExternalStoragePermission = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE);

                // If not grant then require read external storage permission.                if(readExternalStoragePermission != PackageManager.PERMISSION_GRANTED)
                {
                    String requirePermission[] = {Manifest.permission.READ_EXTERNAL_STORAGE};
                    ActivityCompat.requestPermissions(MainActivity.this, requirePermission, REQUEST_CODE_READ_EXTERNAL_PERMISSION);
                }else {
                    selectVideoFile();
                }
            }
        });

        // Click this button to play user browsed or input video file.        playVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                String videoFilePath = videoPathEditor.getText().toString();

                if(!TextUtils.isEmpty(videoFilePath))
                {
                    if(!videoFilePath.trim().toLowerCase().startsWith("http")) {
                        // Play local video file.                        playVideoView.setVideoURI(videoFileUri);
                    }else                    {
                        // Convert the web video url to a Uri object.                        Uri webVideoFileUri = Uri.parse(videoFilePath.trim());

                        // Play web video file use the Uri object.                        playVideoView.setVideoURI(webVideoFileUri);
                    }

                    playVideoView.setVisibility(View.VISIBLE);

                    videoProgressBar.setVisibility(ProgressBar.VISIBLE);

                    currVideoPosition = 0;

                    playVideoView.start();

                    playVideoButton.setEnabled(false);

                    stopVideoButton.setEnabled(true);

                    pauseVideoButton.setEnabled(true);

                    continueVideoButton.setEnabled(false);

                    replayVideoButton.setEnabled(true);
                }

            }
        });

        // Click this button to stop playing video file.        stopVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                // Stop video playing.                playVideoView.stopPlayback();

                // Seek to the beginning of the video file.                playVideoView.seekTo(0);

                playVideoButton.setEnabled(true);

                stopVideoButton.setEnabled(false);

                pauseVideoButton.setEnabled(false);

                continueVideoButton.setEnabled(false);

                replayVideoButton.setEnabled(false);
            }
        });

        // Click this button to pause playing video file.        pauseVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                // Pause video play.                playVideoView.pause();

                isVideoPaused = true;

                // Record current video play position.                currVideoPosition = playVideoView.getCurrentPosition();

                playVideoButton.setEnabled(false);

                stopVideoButton.setEnabled(true);

                pauseVideoButton.setEnabled(false);

                continueVideoButton.setEnabled(true);

                replayVideoButton.setEnabled(true);
            }
        });

        // Click this button to continue play paused video.        continueVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                playVideoView.seekTo(currVideoPosition);

                playVideoButton.setEnabled(false);

                pauseVideoButton.setEnabled(true);

                stopVideoButton.setEnabled(true);

                continueVideoButton.setEnabled(false);

                replayVideoButton.setEnabled(true);
            }
        });

        // Click this button to replay video file.        replayVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {

                // Replay video.                playVideoView.resume();

                // Set current video play position to 0.                currVideoPosition = 0;

                playVideoButton.setEnabled(false);

                pauseVideoButton.setEnabled(true);

                stopVideoButton.setEnabled(true);

                continueVideoButton.setEnabled(false);

                replayVideoButton.setEnabled(true);
            }
        });
    }

    /*      Initialise play video example controls.    * */    private void initVideoControls()
    {
        if(videoPathEditor==null)
        {
            videoPathEditor = (EditText) findViewById(R.id.play_video_file_path_editor);
        }

        if(browseVideoFileButton==null)
        {
            browseVideoFileButton = (Button)findViewById(R.id.browse_video_file_button);
        }

        if(playVideoButton==null)
        {
            playVideoButton = (Button)findViewById(R.id.play_video_start_button);
        }

        if(stopVideoButton==null)
        {
            stopVideoButton = (Button)findViewById(R.id.play_video_stop_button);
        }

        if(pauseVideoButton==null)
        {
            pauseVideoButton = (Button)findViewById(R.id.play_video_pause_button);
        }

        if(continueVideoButton==null)
        {
            continueVideoButton = (Button)findViewById(R.id.play_video_continue_button);
        }

        if(replayVideoButton==null)
        {
            replayVideoButton = (Button)findViewById(R.id.play_video_replay_button);
        }

        if(playVideoView==null)
        {
            playVideoView = (VideoView)findViewById(R.id.play_video_view);
        }

        if(videoProgressBar==null)
        {
            videoProgressBar = (ProgressBar) findViewById(R.id.play_video_progressbar);
        }

        if(videoProgressHandler==null)
        {
            // This handler wait and receive update progress bar message from child thread.            videoProgressHandler = new Handler(){
                @Override                public void handleMessage(Message msg) {
                    // When receive update progressbar message.                    if(msg.what == UPDATE_VIDEO_PROGRESS_BAR)
                    {
                        // Get current video play position.                        int currVideoPosition = playVideoView.getCurrentPosition();

                        // Get total video length.                        int videoDuration = playVideoView.getDuration();

                        // Calculate the percentage.                        int progressPercent = currVideoPosition * 100 / videoDuration;

                        // 10 times percentage value to make effect clear.                        videoProgressBar.setProgress(progressPercent);
                    }
                }
            };

            // This thread send update video progress message to video progress Handler every 2 seconds.            Thread updateProgressThread = new Thread()
            {
                @Override                public void run() {

                    try {
                        while (true) {
                            // Create update video progressbar message.                            Message msg = new Message();
                            msg.what = UPDATE_VIDEO_PROGRESS_BAR;

                            // Send the message to video progressbar update handler.                            videoProgressHandler.sendMessage(msg);

                            // Sleep 2 seconds.                            Thread.sleep(2000);
                        }
                    }catch (InterruptedException ex)
                    {
                        ex.printStackTrace();
                    }
                }
            };
            // Start the thread.            updateProgressThread.start();
        }

        setContinueVideoAfterSeekComplete();
    }

    /* This method start get content activity to let user select video file from local directory.*/    private void selectVideoFile()
    {
        // Create an intent with action ACTION_GET_CONTENT.        Intent selectVideoIntent = new Intent(Intent.ACTION_GET_CONTENT);

        // Show video in the content browser.        // Set selectVideoIntent.setType("*/*") to select all data        // Intent for this action must set content type, otherwise you will encounter below exception : android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.GET_CONTENT }        selectVideoIntent.setType("video/*");

        // Start android get content activity ( this is a android os built-in activity.) .        startActivityForResult(selectVideoIntent, REQUEST_CODE_SELECT_VIDEO_FILE);
    }

    /* This method will be invoked when startActivityForResult method complete in selectVideoFile() method.     *  It is used to process activity result that is started by startActivityForResult method.     * */    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        // Identify activity by request code.        if(requestCode == REQUEST_CODE_SELECT_VIDEO_FILE)
        {
            // If the request is success.            if(resultCode==RESULT_OK)
            {
                // To make example simple and clear, we only choose video file from local file,                // this is easy to get video file real local path.                // If you want to get video file real local path from a video content provider                // Please read another article.                videoFileUri = data.getData();

                String videoFileName = videoFileUri.getLastPathSegment();

                videoPathEditor.setText("You select video file is " + videoFileName);

                playVideoButton.setEnabled(true);

                pauseVideoButton.setEnabled(false);

                replayVideoButton.setEnabled(false);
            }
        }
    }

    /* Run this method after user choose grant read external storage permission or not. */    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode==REQUEST_CODE_READ_EXTERNAL_PERMISSION)
        {
            if(grantResults.length > 0)
            {
                int grantResult = grantResults[0];
                if(grantResult == PackageManager.PERMISSION_GRANTED)
                {
                    // If user grant the permission then open browser let user select audio file.                    selectVideoFile();
                }else                {
                    Toast.makeText(getApplicationContext(), "You denied read external storage permission.", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /* This method is used to play video after seek complete, otherwise video playing will not be accurate.*/    private void setContinueVideoAfterSeekComplete()
    {
        playVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                    @Override                    public void onSeekComplete(MediaPlayer mediaPlayer) {
                        if(isVideoPaused)
                        {
                            playVideoView.start();
                            isVideoPaused = false;
                        }
                    }
                });
            }
        });
    }
}





activity main.xml





<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">

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

        <EditText            android:id="@+id/play_video_file_path_editor"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:hint="enter" />

        <Button            android:id="@+id/browse_video_file_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Video list"/>

        <Button            android:id="@+id/play_video_start_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Play Video"            android:enabled="false"/>

        <Button            android:id="@+id/play_video_stop_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Stop"            android:enabled="false"/>

        <Button            android:id="@+id/play_video_pause_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Pause"            android:enabled="false"/>

        <Button            android:id="@+id/play_video_continue_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Continue"            android:enabled="false"/>

        <Button            android:id="@+id/play_video_replay_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Replay"            android:enabled="false"/>

        <ProgressBar            android:id="@+id/play_video_progressbar"            style="@android:style/Widget.ProgressBar.Horizontal"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:max="100"            android:visibility="invisible"/>

        <VideoView            android:id="@+id/play_video_view"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:visibility="invisible"/>


    </LinearLayout>

</RelativeLayout>







main fest



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