Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 VideoView 做一個支持進度記憶的播放界面

項目裡需要一個 Android 視頻播放界面,邏輯不複雜,直接看代碼。

布局

act_video_play 裡放一個 VideoView,外層 LinearLayout 鋪黑底並居中:

  1. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 
  2.     android:layout_width="fill_parent" 
  3.     android:layout_height="fill_parent" 
  4.     android:background="#ff000000" 
  5.     android:gravity="center" > 
  6.     <VideoView 
  7.         android:id="@+id/videoView" 
  8.         android:layout_width="wrap_content" 
  9.         android:layout_height="wrap_content" 
  10.         android:layout_gravity="center" /> 
  11. </LinearLayout> 

Activity 代碼

關鍵點是:VideoView 全屏鋪開、掛上 MediaController、顯示 ProgressDialog 直到 onPrepared、並在退出時把當前播放位置回傳給上一頁。

  1. protected void onCreate(Bundle savedInstanceState) { 
  2.     super.onCreate(savedInstanceState); 
  3.     setContentView(R.layout.act_video_play); 
  4.  
  5.     Intent intent = getIntent(); 
  6.     video_url = intent.getStringExtra("video_url"); 
  7.     progress_Title = intent.getStringExtra("title"); 
  8.  
  9.     play_progress = intent.getIntExtra("play_progress", 0); 
  10.     videoView = (VideoView) findViewById(R.id.videoView); 
  11.     progress = ProgressDialog.show(this, "loading", progress_Title); 
  12.  
  13.     videoView.setVideoURI(Uri.parse(video_url)); 
  14.     MediaController controller = new MediaController(this); 
  15.     videoView.setMediaController(controller); 
  16.     videoView.requestFocus(); 
  17.  
  18.     videoView.setLayoutParams(new LinearLayout.LayoutParams( 
  19.         LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); 
  20.  
  21.     videoView.setOnPreparedListener(new OnPreparedListener() { 
  22.         public void onPrepared(MediaPlayer mp) { 
  23.             if (progress != null) progress.dismiss(); 
  24.         } 
  25.     }); 
  26. } 

進度回傳靠 onKeyDown 攔截返回鍵,把 videoView.getCurrentPosition() 塞進 Intent 後 setResult:

  1. public boolean onKeyDown(int keyCode, KeyEvent event) { 
  2.     if (keyCode == KeyEvent.KEYCODE_BACK) { 
  3.         Intent intent = new Intent(); 
  4.         intent.putExtra("play_progress", videoView.getCurrentPosition()); 
  5.         setResult(RESULT_OK, intent); 
  6.     } 
  7.     return super.onKeyDown(keyCode, event); 
  8. } 

onResume 裡 seekTo(play_progress) 再 start,onStop 裡 pause 並記錄位置、順手 dismiss 掉進度框,就實現了「從上次停下的地方續播」。

video_url 既可以是本地文件路徑也可以是網絡鏈接(網絡流記得加 INTERNET 權限)。至於進度怎麼持久化,SharedPreferences 或數據庫都行,按實際業務設計即可。

更多 Android 相關內容見 Android 專題頁面 https://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved