項目裡需要一個 Android 視頻播放界面,邏輯不複雜,直接看代碼。
布局
act_video_play 裡放一個 VideoView,外層 LinearLayout 鋪黑底並居中:
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#ff000000"
- android:gravity="center" >
- <VideoView
- android:id="@+id/videoView"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center" />
- </LinearLayout>
Activity 代碼
關鍵點是:VideoView 全屏鋪開、掛上 MediaController、顯示 ProgressDialog 直到 onPrepared、並在退出時把當前播放位置回傳給上一頁。
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.act_video_play);
-
- Intent intent = getIntent();
- video_url = intent.getStringExtra("video_url");
- progress_Title = intent.getStringExtra("title");
-
- play_progress = intent.getIntExtra("play_progress", 0);
- videoView = (VideoView) findViewById(R.id.videoView);
- progress = ProgressDialog.show(this, "loading", progress_Title);
-
- videoView.setVideoURI(Uri.parse(video_url));
- MediaController controller = new MediaController(this);
- videoView.setMediaController(controller);
- videoView.requestFocus();
-
- videoView.setLayoutParams(new LinearLayout.LayoutParams(
- LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
-
- videoView.setOnPreparedListener(new OnPreparedListener() {
- public void onPrepared(MediaPlayer mp) {
- if (progress != null) progress.dismiss();
- }
- });
- }
進度回傳靠 onKeyDown 攔截返回鍵,把 videoView.getCurrentPosition() 塞進 Intent 後 setResult:
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- Intent intent = new Intent();
- intent.putExtra("play_progress", videoView.getCurrentPosition());
- setResult(RESULT_OK, intent);
- }
- return super.onKeyDown(keyCode, event);
- }
onResume 裡 seekTo(play_progress) 再 start,onStop 裡 pause 並記錄位置、順手 dismiss 掉進度框,就實現了「從上次停下的地方續播」。
video_url 既可以是本地文件路徑也可以是網絡鏈接(網絡流記得加 INTERNET 權限)。至於進度怎麼持久化,SharedPreferences 或數據庫都行,按實際業務設計即可。
更多 Android 相關內容見 Android 專題頁面 https://www.linuxidc.com/topicnews.aspx?tid=11