浅谈Android播放器的实现方法与小项目的开发举例

浅谈Android播放器的实现方法与小项目的开发举例


在Android中,通常有三种方式来实现视频播放:

1、使用其自带的播放器。指定Action为ACTION_VIEW,Data为Uri,Type为其MIME类型。
2、使用VideoView来播放。在布局文件中使用VideoView结合MediaController来实现对其控制。

3、使用MediaPlayer类和SurfaceView来实现,这种方式很灵活。

下面分别阐述这三种实现方法:

1、调用自带的播放器

Android有其自带的播放器,我们可以使用隐式Intent来调用它:通过传入一个Action为ACTION_VIEW同时,指定Data为所要播放的视频的Uri对象,并指定格式信息,则我们就可以调用播放器来播放视频了。

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri, MimeType);

startActivity(intent);

Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/Test_Movie.m4v");//调用系统自带的播放器
    Intent intent = new Intent(Intent.ACTION_VIEW);    
    Log.v("URI:", uri.toString());    
    intent.setDataAndType(uri, "video/mp4");    

    startActivity(intent);   

布局代码:

<?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:id="@+id/activity_main2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.video.Main2Activity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/et2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:hint="请输入文件名"/>

        <Button
            android:id="@+id/btn1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="确定"/>
    </LinearLayout>

    <io.vov.vitamio.widget.VideoView
        android:id="@+id/video1"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_marginTop="10dp"/>

</LinearLayout>
 

效果图:


2、使用VideoView来实现:

VideoView 系统自带的视频播放控件,自带进度条、暂停、播放等功能,使用起来十分简单,只需要为控件设置好播放路径,监听是否准备就绪,就绪后直接播放就可以了。

Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/Test_Movie.m4v");
VideoView videoView = (VideoView)this.findViewById(R.id.video_view);
videoView.setMediaController(new MediaController(this));    
videoView.setVideoURI(uri);    
videoView.start();    

videoView.requestFocus(); 

布局代码:

<?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:id="@+id/activity_main2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.video.Main2Activity"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/et1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:hint="请输入文件名"/>

        <Button
            android:id="@+id/btn"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="确定"/>
    </LinearLayout>

    <VideoView
        android:id="@+id/video"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_marginTop="10dp"/>

</LinearLayout>

主框架代码:

package com.example.video;

import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.VideoView;

import java.net.URI;

public class Main2Activity extends Activity {

    private VideoView video;
    private EditText et;
    private Button btn;

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

        initView();
    }

    private void initView() {
        et = (EditText) findViewById(R.id.et1);
        video = (VideoView) findViewById(R.id.video);
        btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String path = Environment.getExternalStorageDirectory().getPath()+"/"+et.getText().toString();//获取视频路径
                Uri uri = Uri.parse(path);//将路径转换成uri
                video.setVideoURI(uri);//为视频播放器设置视频路径
                video.setMediaController(new MediaController(Main2Activity.this));//显示控制栏
                video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        video.start();//开始播放视频
                    }
                });
            }
        });
    }
}

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.VideoView;
public class VideoBusiness implements MediaPlayer.OnPreparedListener,MediaPlayer.OnCompletionListener,MediaPlayer.OnErrorListener{

    private Activity activity;
    private WakeLock mWakeLock;
    public  VideoView mVideoView;
    private VideoController mController;

    /**播放状态枚举,有三种播放状态:空闲,正在准备*/
    private enum PLAYER_STATUS {
        IDLE, PREPARING,PAUSED, PREPARED,RESUMED,STOPPED
    }
    /**当前播放状态*/
    public  PLAYER_STATUS mPlayerStatus = PLAYER_STATUS.IDLE;

    /**播放信息异步处理方法,用于更新进度*/
    /**事件标志*/
    private int mLastPos;

    public VideoBusiness(Activity activity){
        this.activity = activity;
        // 保持屏幕高亮
        PowerManager pm = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "Test");
    }

    //初始化视频播放器
    public void initVideo(VideoView videoView,VideoController controller,String sourceUrl){

        this.mVideoView = videoView;
        this.mController = controller;
        mController.setVideoBusiness(this);
        Log.e("msg","设置播放地址 = "+sourceUrl);
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnErrorListener(this);
        mVideoView.setVideoPath(sourceUrl); //设置播放地址

    }

    //开始播放
    public void startPlay(){
        if (null != mWakeLock && (!mWakeLock.isHeld())) {
            mWakeLock.acquire();
        }
        if(null != mVideoView) {
            Log.e("msg", "播放");
            mVideoView.start();
            mPlayerStatus = PLAYER_STATUS.PREPARING;
        }
    }


    /**
     * 暂停播放
     */
    public void pause() {
        if (null != mWakeLock) {
            mWakeLock.release();
        }
        if(null != mVideoView && mVideoView.isPlaying()){
            mVideoView.pause();
            mPlayerStatus = PLAYER_STATUS.PAUSED;
            mLastPos = getCurrentTime();
        }
    }

    /**
     * 继续播放
     */
    public void resume(){
        if (null != mWakeLock) {
            mWakeLock.acquire();
        }
        if(null != mVideoView){
            //mVideoView.resume();
            mVideoView.seekTo(mLastPos);
            mVideoView.start();
            mPlayerStatus = PLAYER_STATUS.RESUMED;
        }
    }

    /**
     * 停止播放
     */
    public void stop() {

        if (null != mWakeLock) {
            mWakeLock.release();
        }
        if(null != mVideoView){
            mLastPos = getCurrentTime();
            mVideoView.stopPlayback();
            mPlayerStatus = PLAYER_STATUS.STOPPED;
        }
    }

    /**
     * 判断是否正在播放
     * @return
     */
    public boolean isPlaying(){
        return mVideoView!=null && mVideoView.isPlaying();
    }

    /**
     * 是否暂停
     */
    public boolean isPause(){
        return mPlayerStatus == PLAYER_STATUS.PAUSED;
    }

    /**
     * 释放资源
     */
    public void release(){
        if (null != mWakeLock) {
            mWakeLock.release();
            mWakeLock = null;
        }
        if(null != mVideoView){
            mVideoView.stopPlayback();
            mVideoView = null;
        }
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        Log.e("onCompletion","视频播放完了");
        mController.showLong();
        mController.setProgress(0);
        mLastPos = 0;
        mPlayerStatus = PLAYER_STATUS.IDLE;
        removeUIMessage();
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
        Log.e("onError","视频播放报错了");
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        Log.e("onPrepared","视频准备好了");
        if (mPlayerStatus!= PLAYER_STATUS.PAUSED){
            int totalTime = getTotalTime();
            mController.setTotalTime(totalTime);
            mController.setProgress(0);
            mController.setMaxProgress(totalTime);
            mPlayerStatus = PLAYER_STATUS.PREPARED;
            sendUIMessage();
        }
    }

    /**
     * 进度条拖拽播放
     * @param time
     */
    public void seekToPlay(int time){
        int totalSecond = getTotalTime();
        int tempTime = time > totalSecond ? totalSecond : time;
        mVideoView.seekTo(tempTime);
        sendUIMessage();
    }


    //视频暂停播放 播放大按钮点击事件
    public void playVideo(ImageView id_btn_video_play, ImageView img){
        if(isPlaying()){
            pause();
            id_btn_video_play.setVisibility(View.VISIBLE);
            img.setImageResource(R.drawable.video_pause);
            mPlayerStatus = PLAYER_STATUS.PAUSED;
            mUIHandler.sendEmptyMessageDelayed(UI_EVENT_UPDATE_CURRPOSITION, 500);
        }else if(isPause()){
            resume();
            id_btn_video_play.setVisibility(View.GONE);
            img.setImageResource(R.drawable.video_play);
            mPlayerStatus = PLAYER_STATUS.RESUMED;
        }else{
            img.setImageResource(R.drawable.video_play);
            id_btn_video_play.setVisibility(View.GONE);
            startPlay();
            mPlayerStatus = PLAYER_STATUS.PREPARING;
        }
    }

    private boolean isCurrentLandscape = false;  //是不是横屏
    //横竖屏切换按钮点击方法
    public void toggleScreenDir(View v){
        if (isCurrentLandscape) {// 如果当前是横屏,则切换为竖屏,然后把按钮为变为变大的图标
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            if(v instanceof ImageView){
                ((ImageView)v).setImageResource(R.drawable.zuidahua_2x);
            }
        } else {// 如果当前是竖屏,则切换为横屏,然后把按钮为变为变小的图标
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            if(v instanceof ImageView){
                ((ImageView)v).setImageResource(R.drawable.xiaohua_2x);
            }
        }
        isCurrentLandscape = !isCurrentLandscape;
    }

    public UIHandler mUIHandler = new UIHandler(Looper.getMainLooper());
    public final int UI_EVENT_UPDATE_CURRPOSITION = 1;  //更新进度信息
    public boolean isSeekBarEnable = true;

    class UIHandler extends Handler{
        public UIHandler(Looper mainLooper) {
            super(mainLooper);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //更新进度及时间
                case UI_EVENT_UPDATE_CURRPOSITION:
                    if (isSeekBarEnable) {
                        int currentPosition = getCurrentTime();
                        String timeString = mController.getTimeString(currentPosition);
                        //Log.e("handleMessage",timeString);
                        if(isPlaying()) {
                            mController.setProgress(currentPosition);
                            mUIHandler.sendEmptyMessageDelayed(
                                    UI_EVENT_UPDATE_CURRPOSITION, 200);
                        }
                    }
                    break;
            }
        }
    }

    public void sendUIMessage(){
        mUIHandler.sendEmptyMessage(UI_EVENT_UPDATE_CURRPOSITION);
    }

    public void removeUIMessage(){
        mUIHandler.removeMessages(UI_EVENT_UPDATE_CURRPOSITION);
    }

    //获取视频总时间
    public int getTotalTime(){
        return mVideoView==null ? 0 : mVideoView.getDuration();
    }

    //获取视频当前时间
    public int getCurrentTime(){
        return mVideoView==null ? 0 : mVideoView.getCurrentPosition();
    }
}

效果图:


3、使用MediaPlayer

MediaPlayer,是用于媒体文件播放的组件。Android中MediaPlayer通常与SurfaceView一起使用,当然也可以和其他控件诸如TextureView、SurfaceTexture等可以取得holder,用于MediaPlayer.setDisplay的控件一起使用。

MediaPlayer是媒体播放器,可以播放音频,视频其实就是给音频配上影像,而SurfaceView就是给音频配上影像的工具,我们只需要把SurfaceView与MediaPlayer关联起来就行了。

布局代码:

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.video.MainActivity"
    android:layout_margin="10dp"
    android:orientation="vertical">

    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入文件名称例如:aa.mp4,务必确保文件放在sdcard目录下"/>

    <SurfaceView
        android:id="@+id/sfv"
        android:layout_width="match_parent"
        android:layout_marginTop="10dp"
        android:layout_height="200dp" />

    <SeekBar
        android:id="@+id/sb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/play"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_weight="1"
            android:onClick="play"
            android:text="播放"/>

        <Button
            android:id="@+id/pause"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:onClick="pause"
            android:text="暂停"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:onClick="stop"
            android:text="停止"/>

        <Button
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:onClick="replay"
            android:text="重播"/>

    </LinearLayout>

</LinearLayout>

主框架代码:

package com.example.video;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {

    private SurfaceView sfv;//能够播放图像的控件
    private SeekBar sb;//进度条
    private String path ;//本地文件路径
    private SurfaceHolder holder;
    private MediaPlayer player;//媒体播放器
    private Button Play;//播放按钮
    private Timer timer;//定时器
    private TimerTask task;//定时器任务
    private int position = 0;
    private EditText et;

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

        initView();
    }

    //初始化控件,并且为进度条和图像控件添加监听
    private void initView() {
        sfv = (SurfaceView) findViewById(R.id.sfv);
        sb = (SeekBar) findViewById(R.id.sb);
        Play = (Button) findViewById(R.id.play);
        et = (EditText) findViewById(R.id.et);
        Play.setEnabled(false);

        holder = sfv.getHolder();
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //当进度条停止拖动的时候,把媒体播放器的进度跳转到进度条对应的进度
                if (player != null) {
                    player.seekTo(seekBar.getProgress());
                }
            }
        });

        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                //为了避免图像控件还没有创建成功,用户就开始播放视频,造成程序异常,所以在创建成功后才使播放按钮可点击
                Log.d("zhangdi","surfaceCreated");
                Play.setEnabled(true);
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.d("zhangdi","surfaceChanged");
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                //当程序没有退出,但不在前台运行时,因为surfaceview很耗费空间,所以会自动销毁,
                // 这样就会出现当你再次点击进程序的时候点击播放按钮,声音继续播放,却没有图像
                //为了避免这种不友好的问题,简单的解决方式就是只要surfaceview销毁,我就把媒体播放器等
                //都销毁掉,这样每次进来都会重新播放,当然更好的做法是在这里再记录一下当前的播放位置,
                //每次点击进来的时候把位置赋给媒体播放器,很简单加个全局变量就行了。
                Log.d("zhangdi","surfaceDestroyed");
                if (player != null) {
                    position = player.getCurrentPosition();
                    stop();
                }
            }
        });
    }

    private void play() {

        Play.setEnabled(false);//在播放时不允许再点击播放按钮

        if (isPause) {//如果是暂停状态下播放,直接start
            isPause = false;
            player.start();
            return;
        }

        path = Environment.getExternalStorageDirectory().getPath()+"/";
        path = path + et.getText().toString();//sdcard的路径加上文件名称是文件全路径
        File file = new File(path);
        if (!file.exists()) {//判断需要播放的文件路径是否存在,不存在退出播放流程
            Toast.makeText(this,"文件路径不存在",Toast.LENGTH_LONG).show();
            return;
        }

        try {
            player = new MediaPlayer();
            player.setDataSource(path);
            player.setDisplay(holder);//将影像播放控件与媒体播放控件关联起来

            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {//视频播放完成后,释放资源
                    Play.setEnabled(true);
                    stop();
                }
            });

            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    //媒体播放器就绪后,设置进度条总长度,开启计时器不断更新进度条,播放视频
                    Log.d("zhangdi","onPrepared");
                    sb.setMax(player.getDuration());
                    timer = new Timer();
                    task = new TimerTask() {
                        @Override
                        public void run() {
                            if (player != null) {
                                int time = player.getCurrentPosition();
                                sb.setProgress(time);
                            }
                        }
                    };
                    timer.schedule(task,0,500);
                    sb.setProgress(position);
                    player.seekTo(position);
                    player.start();
                }
            });

            player.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void play(View v) {
        play();
        Log.d("zhangdi",path);
    }

    private boolean isPause;
    private void pause() {
        if (player != null && player.isPlaying()) {
            player.pause();
            isPause = true;
            Play.setEnabled(true);
        }
    }

    public void pause(View v) {
        pause();
    }

    private void replay() {
        isPause = false;
        if (player != null) {
            stop();
            play();
        }
    }

    public void replay(View v) {
        replay();
    }

    private void stop(){
        isPause = false;
        if (player != null) {
            sb.setProgress(0);
            player.stop();
            player.release();
            player = null;
            if (timer != null) {
                timer.cancel();
            }
            Play.setEnabled(true);
        }
    }

    public void stop(View v) {
        stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stop();
    }
}

效果图:


二、项目开发举例

activity_main.xml

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

<TextView
android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/textview"
        android:textColor="#9999CC"
        android:textSize="21sp" />

<!-- 定义SurfaceView组件 -->

<SurfaceView
android:id="@+id/surfaceView1"
        android:layout_width="match_parent"
        android:layout_height="380dp"
        android:keepScreenOn="true" />

<!-- 在水平线性布局里 定义3个按钮组件,分别为播放,暂停,停止,退出按钮 -->

<LinearLayout
android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="horizontal" >

<Button
android:id="@+id/play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="@string/play" />

<Button
android:id="@+id/pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="@string/pause" />

<Button
android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="@string/stop" />

<Button
android:id="@+id/finish"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="click"
        android:text="@string/finish" />
</LinearLayout>

</LinearLayout>

MainActivity

package com.example.videotest1;

import com.example.service.ServiceTest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    public static SurfaceView sv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sv = (SurfaceView) findViewById(R.id.surfaceView1);// 获得SurfaceView控件
    }

    /*
     *点击那4个按钮后触发的事件 
     */
    public void click(View v) {
        Intent intent = new Intent(MainActivity.this, ServiceTest.class);
        int op = -1;// 定义一个中间变量
        switch (v.getId()) {
            case R.id.play:
                op = 1;
                Toast.makeText(MainActivity.this, "视频正在播放...", Toast.LENGTH_SHORT)
                        .show();
                break;
            case R.id.pause:
                op = 2;
                Toast.makeText(MainActivity.this, "视频暂停播放...", Toast.LENGTH_SHORT)
                        .show();
                break;
            case R.id.stop:
                op = 3;
                Toast.makeText(MainActivity.this, "视频停止播放...", Toast.LENGTH_SHORT)
                        .show();
                break;
            case R.id.finish:
                if (intent != null) {
                    stopService(intent);
                }
                finish();
                break;
            default:
                break;
        }
        Bundle bundle = new Bundle();// 声明一个Bundle对象并实例化
        bundle.putInt("middle", op);// 把中间变量op放置到middle这个键
        intent.putExtras(bundle);// 用intent把bundle放入进去
        startService(intent);// 开始服务
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

ServiceTest

package com.example.service;


import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;

public class ServiceTest extends Service {

    public static MediaPlayer player;// 声明MediaPlayer对象

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    // 创建服务
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        if (player == null) {
            try {
                player = new MediaPlayer();//实例化MediaPlayer对象
                player.setDataSource("/sdcard/wf2.mp4");// 设置要播放的视频
                player.setLooping(false);// 设置视频不循环播放
                super.onCreate();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    // 开始服务
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Bundle bundle = intent.getExtras();// 获得从MainActivity传来的bundle对象
        int op = bundle.getInt("middle");// 获得从MainActivity.java里传递过来的op
        switch (op) {
            case 1:// 当op为1,即点击了播放按钮
                play();// 调用play()方法
                break;
            case 2:// 当op为2,即点击了暂停按钮
                pause();// 调用pause()方法
                break;
            case 3:// 当op为3,即点击了停止按钮
                stop();// 调用stop()方法
                break;
            default:
                break;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    // 播放视频play()方法
    private void play() {
        // TODO Auto-generated method stub
        if (player != null && !player.isPlaying()) {
            player.setDisplay(com.example.videotest1.MainActivity.sv
                    .getHolder());//把视频画面显示出来
            try {
                player.prepare();//预加载视频
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            player.start();// 开始播放音乐
        }
    }

    private void pause() {
        // TODO Auto-generated method stub
        if (player != null && player.isPlaying()) {
            player.pause();// 暂停视频的播放
        }
    }

    private void stop() {
        // TODO Auto-generated method stub
        if (player != null) {
            player.seekTo(0);//如果点击播放按钮的话会从头播放
            player.stop();// 停止音乐的播放
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        if (player != null) {
            player.stop();//停止播放视频
            player.release();// 释放资源
            player = null;
        }
        super.onDestroy();
    }
}

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">VideoTest1</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="play">播放</string>
<string name="pause">暂停</string>
<string name="stop">停止</string>
<string name="finish">退出</string>
</resources>

效果图:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值