导读
1.用Intent方式实现播放
2.用VideoView实现播放
3.用MediaPlayer实现播放
⚠️三个案例放在了一个工程中
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hala.videoplayer">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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>
<activity android:name=".VideoViewActivity" />
<activity android:name=".MediaPlayerActivity"></activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/id_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hala.videoplayer.MainActivity">
</ListView>
item_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/id_tv_title"
android:layout_width="match_parent"
android:layout_height="56dp"
android:gravity="center_vertical"
android:orientation="vertical"
android:textSize="22dp">
</TextView>
MainActivity.java
package com.hala.videoplayer;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private List<String> mDatas = Arrays.asList("Use Intent",
"Use VideoView", "Use MediaPlayer & SurfaceView");
private static final int REQ_CODE_STORAGE = 0x110;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.id_listview);
mListView.setAdapter(
new ArrayAdapter<String>(this, R.layout.item_main,
R.id.id_tv_title, mDatas));
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
checkPermissionAndPlayVideo();
break;
case 1:
VideoViewActivity.start(MainActivity.this);
break;
case 2:
MediaPlayerActivity.start(MainActivity.this);
break;
default:
break;
}
}
});
}
private void checkPermissionAndPlayVideo() {
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQ_CODE_STORAGE);
} else {
playVideoUseIntent();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQ_CODE_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
playVideoUseIntent();
} else {
Toast.makeText(this, "该功能需要SDCard权限", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
private void playVideoUseIntent() {
File file = new File(Environment.getExternalStorageDirectory().getPath(), "ww.mp4");
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= 24) {
Uri contentUri = FileProvider.getUriForFile(this, "com.imooc.videotest.fileprovider", file);
intent.setDataAndType(contentUri, "video/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} else {
intent.setDataAndType(Uri.fromFile(file), "video/*");
}
startActivity(intent);
}
}
activity_video_view.xml
<?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_video_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hala.videoplayer.VideoViewActivity">
<VideoView
android:id="@+id/id_videoview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
VideoViewActivity.java
package com.hala.videoplayer;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
import java.io.File;
public class VideoViewActivity extends AppCompatActivity {
private VideoView mVideoView;
private MediaController mMediaController;
private static final String KEY_CUR_POS = "key_cur_pos";
private static final String KEY_IS_PAUSE = "key_is_pause";
private int mCurrentPos;
private boolean mIsPause;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_view);
mVideoView = (VideoView) findViewById(R.id.id_videoview);
File file = new File(Environment.getExternalStorageDirectory().getPath(), "lalala.mp4");
mVideoView.setVideoPath(file.getAbsolutePath());
mMediaController = new MediaController(this);
mVideoView.setMediaController(mMediaController);
}
@Override
protected void onResume() {
super.onResume();
mVideoView.seekTo(mCurrentPos);
if (!mIsPause) {
mVideoView.start();
}
}
@Override
protected void onPause() {
super.onPause();
mCurrentPos = mVideoView.getCurrentPosition();
mIsPause = !mVideoView.isPlaying();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_CUR_POS, mCurrentPos);
outState.putBoolean(KEY_IS_PAUSE, mIsPause);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentPos = savedInstanceState.getInt(KEY_CUR_POS);
mIsPause = savedInstanceState.getBoolean(KEY_IS_PAUSE);
}
public static void start(Context context) {
Intent intent = new Intent(context, VideoViewActivity.class);
context.startActivity(intent);
}
}
activity_media_player.xml
<?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_media_player"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hala.videoplayer.MediaPlayerActivity">
<RelativeLayout
android:id="@+id/id_rl_container"
android:layout_width="match_parent"
android:layout_height="200dp">
<SurfaceView
android:id="@+id/id_surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<SeekBar
android:id="@+id/id_seekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="4dp"/>
<Button
android:layout_width="wrap_content"
android:id="@+id/id_btn_play"
android:enabled="false"
android:text="暂停"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:minHeight="0dp"
android:minWidth="0dp"
android:layout_height="wrap_content" />
</RelativeLayout>
</RelativeLayout>
MediaPlayerActivity.java
package com.hala.videoplayer;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import java.io.File;
import java.io.IOException;
public class MediaPlayerActivity extends AppCompatActivity {
private RelativeLayout mRlContainer;
private SurfaceView mSurfaceView;
private SeekBar mSeekBar;
private Button mBtnPlay;
private MediaPlayer mMediaPlayer;
private boolean mIsPrepared;
private boolean mIsPause;
private float mRatioHW;
private Handler mHandler = new Handler();
private Runnable mUpdateProgressRunnable = new Runnable() {
@Override
public void run() {
if (mMediaPlayer == null) {
return;
}
int currentPosition = mMediaPlayer.getCurrentPosition();
int duration = mMediaPlayer.getDuration();
if (mSeekBar != null && duration > 0) {
int progress = (int) (currentPosition * 1.0f / duration * 1000);
mSeekBar.setProgress(progress);
if (mMediaPlayer.isPlaying()) {
mHandler.postDelayed(mUpdateProgressRunnable, 1000);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
initViews();
initMediaPlayer();
initEvents();
}
private void initEvents() {
mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
mMediaPlayer.setDisplay(holder);
if (!mIsPrepared) {
return;
}
if (mIsPause) {
mMediaPlayer.seekTo(mMediaPlayer.getCurrentPosition());
return;
}
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
mHandler.post(mUpdateProgressRunnable);
mBtnPlay.setText("暂停");
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateProgressRunnable);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
long duration = mMediaPlayer.getDuration();
int targetPos = (int) (seekBar.getProgress() * 1.0f / 1000 * duration);
mMediaPlayer.seekTo(targetPos);
if (mMediaPlayer.isPlaying()) {
mHandler.post(mUpdateProgressRunnable);
}
}
});
mBtnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mBtnPlay.setText("播放");
mHandler.removeCallbacks(mUpdateProgressRunnable);
mIsPause = true;
} else {
mMediaPlayer.start();
mBtnPlay.setText("暂停");
mHandler.post(mUpdateProgressRunnable);
mIsPause = false;
}
}
});
}
private void initMediaPlayer() {
mMediaPlayer = new MediaPlayer();
File file = new File(Environment.getExternalStorageDirectory().getPath(), "lalala.mp4");
try {
mMediaPlayer.setDataSource(file.getAbsolutePath());
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mIsPrepared = true;
mBtnPlay.setEnabled(true);
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
mBtnPlay.setText("暂停");
mHandler.post(mUpdateProgressRunnable);
}
}
});
mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
@Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
ViewGroup.LayoutParams lp = mRlContainer.getLayoutParams();
mRatioHW = height * 1.0f / width;
lp.height = (int) (mRlContainer.getWidth() * 1.0f / width * height);
mRlContainer.setLayoutParams(lp);
}
});
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mHandler.removeCallbacks(mUpdateProgressRunnable);
mSeekBar.setProgress(1000);
mBtnPlay.setText("播放");
mIsPause = true;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
mMediaPlayer.pause();
mHandler.removeCallbacks(mUpdateProgressRunnable);
}
@Override
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.release();
}
@Override
protected void onResume() {
super.onResume();
}
private void initViews() {
mRlContainer = (RelativeLayout) findViewById(R.id.id_rl_container);
mSurfaceView = (SurfaceView) findViewById(R.id.id_surface_view);
mSeekBar = (SeekBar) findViewById(R.id.id_seekbar);
mBtnPlay = (Button) findViewById(R.id.id_btn_play);
mSeekBar.setMax(1000);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
ViewTreeObserver observer = mRlContainer.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mRlContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
ViewGroup.LayoutParams lp = mRlContainer.getLayoutParams();
lp.height = (int) (mRatioHW * mRlContainer.getWidth());
mRlContainer.setLayoutParams(lp);
}
});
}
public static void start(Context context) {
Intent intent = new Intent(context, MediaPlayerActivity.class);
context.startActivity(intent);
}
}