Android 之 多媒体播放

新建一个 MediaApp Android 工程



点击文件 调出系统安装的 音频 相册 视频等开始播放




下面我们一步一步实现

复制任意测试图片,mp3音频, mp4 视频到  sdcard 如图:



1. 新建布局文件 res -> layout-> media.xml

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

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         />

</LinearLayout>


3. 新建调用系统媒体应用接口工具类 com.util.COpenFile

package com.util;

import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

public class COpenFile {

	// 通过文件的扩展名 去打开对于的系统的应用程序
	public static void openApp(Context context, String filePath) {
		// 从filePath 获得扩展名 /sdcard/test.txt
		String fileExt = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
		if ("txt".contains(fileExt)) {
			Intent intent = getTextFileIntent(filePath, false);
			context.startActivity(intent);
		}

		if ("png,gif,jpg".contains(fileExt)) {
			Intent intent = getImageFileIntent(filePath);
			context.startActivity(intent);
		}
		if ("mp3".contains(fileExt)) {
			Intent intent = getAudioFileIntent(filePath);
			context.startActivity(intent);
		}

		if ("pdf".contains(fileExt)) {
			Intent intent = getPdfFileIntent(filePath);
			context.startActivity(intent);
		}

		if ("mp4,3gp".contains(fileExt)) {
			Intent intent = getVideoFileIntent(filePath);
			context.startActivity(intent);
		}
	}

	// android获取一个用于打开HTML文件的intent
	public static Intent getHtmlFileIntent(String param) {
		Uri uri = Uri.parse(param).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param).build();
		Intent intent = new Intent("android.intent.action.VIEW");
		// 设置打开 文件的类型
		intent.setDataAndType(uri, "text/html");
		return intent;
	}

	// android获取一个用于打开图片文件的intent
	public static Intent getImageFileIntent(String param) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		// image/* 表示所有的图片
		intent.setDataAndType(uri, "image/*");
		return intent;
	}

	// android获取一个用于打开PDF文件的intent
	public static Intent getPdfFileIntent(String param) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/pdf");
		return intent;
	}

	// android获取一个用于打开文本文件的intent
	public static Intent getTextFileIntent(String param, boolean paramBoolean) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// 如果是 true 从网络打开文件
		if (paramBoolean) {
			Uri uri1 = Uri.parse(param);
			intent.setDataAndType(uri1, "text/plain");
		} else // 如果是 false 从 sdcard 打开文件
		{
			Uri uri2 = Uri.fromFile(new File(param));
			intent.setDataAndType(uri2, "text/plain");
		}
		return intent;
	}

	// android获取一个用于打开音频文件的intent
	public static Intent getAudioFileIntent(String param) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "audio/*");
		return intent;
	}

	// android获取一个用于打开视频文件的intent
	public static Intent getVideoFileIntent(String param) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "video/*");
		return intent;
	}

}




4. 新建保存媒体的模型类 com.test.MediaItem

package com.test;

public class MediaItem {
	private String name;// 文件名称
	private String path;// 路径

	public MediaItem(String name, String path) {
		super();
		this.name = name;
		this.path = path;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String toString() {
		return this.name;
	}

}



5. 新建界面类 com.test.MediaActivity

package com.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.mediaapp.R;
import com.util.COpenFile;

public class MediaActivity extends Activity {
	private ListView listView;
	private List<MediaItem> mediaIemList = new ArrayList<MediaItem>();

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

		listView = (ListView) findViewById(R.id.listView);
		listView.setOnItemClickListener(itemListener);

		filldata();
	}

	private OnItemClickListener itemListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			MediaItem item = mediaIemList.get(position);
			// 调用系统视频播放器
			COpenFile.openApp(MediaActivity.this, item.getPath());

		}

	};

	// 从 sdcard 获得音频数据
	private void filldata() {
		searchMediaIems("/sdcard");
		// 绑定到 listView
		ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mediaIemList);
		listView.setAdapter(adapter);
	}

	private void searchMediaIems(String filePath) {
		File file = new File(filePath);
		// 获得自目录和文件
		File[] files = file.listFiles();
		for (int i = 0; files != null && i < files.length; i++) {

			File item = files[i];
			String name = item.getName();
			String path = item.getAbsolutePath();
			// 如果是文件
			if (item.isFile()) {
				// 获得扩展名
				String ext = name.substring(name.lastIndexOf("."));
				mediaIemList.add(new MediaItem(name, path));
			}
		}
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();
	}
}



6. AndroidManifest.xml 全局配置文件 配置启动界面 com.test.MediaActivity

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mediaapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="7" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <activity
            android:name="com.test.MediaActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
    </application>

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
</manifest>





4. 在 MediaApp 右键 -> Run As -> Android Application 发布到模拟器运行


Easy Learning Java


Easy Learning Design Patterns Java Practice


Easy Learning Data Structures & Algorithms Java Practice


Java Parsing Collection XML JSON


Easy Learning JDBC + MySQL


Easy Learning Javascript


Easy Learning Design Patterns Javascript


Easy Learning Design Patterns ES6+ Javascript


Easy Learning Data Structures & Algorithms Javascript


Easy Learning Data Structures & Algorithms ES6+Javascript


Easy Learning Oracle SQL


Easy Learning JDBC + Oracle


Easy Learning Python 3


Easy Learning Data Structures & Algorithms Python 3


Easy Learning Design Patterns Python 3


Easy Learning HTML CSS


Easy Learning MySQL SQL


Easy Learning C#


Easy Learning Data Structures & Algorithms C#


Easy Learning C


Easy Learning Data Structures & Algorithms C


Easy Learning Data Structures & Algorithms C++

Android 之 多媒体播放