Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Intent 播放本地視頻:把播放工作交給系統播放器

編輯:關於 Android 程式設計

Android 播放視頻大致有三條路:

  1. 使用意圖播放:呼叫本地已安裝的播放器,由使用者挑一個來播。
  2. 使用 VideoView 播放:VideoView 其實是對 MediaPlayer 的封裝,用起來簡單,但靈活性較差。
  3. 使用 MediaPlayer 播放:直接把 MediaPlayer 物件用於視頻播放,能對播放本身提供最大的控制彈性。

本文只講第一種。雖然最終負責播放的機制仍是 MediaPlayer,但那些細節都由系統播放器代勞,我們只需要發一個意圖。

版面配置

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="播放" />

</LinearLayout>

程式碼

package com.multimediademo10videointent;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * 透過意圖觸發內建的媒體播放器進行本地視頻播放
 */
public class MainActivity extends Activity implements OnClickListener {

    private Button button;

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

    /**
     * 點擊按鈕後,由系統選擇已安裝的視頻播放器來播放
     */
    @Override
    public void onClick(View v) {
        /**
         * 使用 Intent.ACTION_VIEW 建立意圖,
         * 並透過 setDataAndType() 傳入檔案的 URI 與 MIME 型別
         */
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        Uri data = Uri.parse(Environment.getExternalStorageDirectory()
                .getPath() + "/1.mp4");
        intent.setDataAndType(data, "video/mp4");
        startActivity(intent);
    }
}

執行前請注意

運行這個程式之前,需要在 SD 卡根目錄放置一個名為 1.mp4 的視頻檔案,否則會因為找不到檔案而無法播放。

另外要提醒兩點現實環境的變化:一是 Environment.getExternalStorageDirectory() 這類直接存取外部儲存的寫法,在 Android 10 以上已受到儲存空間隔離限制,建議改用 MediaStore 或 FileProvider;二是從其他 App 傳入的 URI 若要給 ACTION_VIEW 使用,需加上 FLAG_GRANT_READ_URI_PERMISSION,否則對方會因權限不足而打不開。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved