There are two ways to play video, you can use videoview and midiaplayer to play, because videoview is highly encapsulated and easy to play, so I won’t discuss it here. This article mainly talks about mediaplayer.
Mediaplayer playback requires surfaceview to show the playback interface.
The task to be completed this time is mainly to play pictures or videos in a designated area of the screen, that is: there are multimedia files such as videos and pictures in a queue, and the playback logic is responsible for obtaining each file in the queue. When it is found that the file is a picture, use the picture playback method to play it. When the file is a video, use mediaplayer to play the video.
Because it involves repeatedly creating and destroying the surface, reasonable control is required. After testing and viewing, it is found that the visibility can control the destruction of the surfaceview. But the creation is controlled by the surfaceholder holder.
Then the code for this idea is as follows:
1: Create mediaplayer
if(mediaPlayer==null){
mediaPlayer = new MediaPlayer();< br>}
mediaPlayer.setOnCompletionListener (this);
try {
mediaPlayer.setDataSource (path);
// move
} catch (Exception e) {
e.printStackTrace ();
} }
2: Create surfaceholder
surfaceHolder = hs_surface.getHolder();
surfaceHolder.addCallback(this);
3: Play mediaplayer when the surface is created
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.v(“surfaceCreated”, “surfaceCreated”);
surfaceHolder = holder;
mediaPlayer.setDisplay(holder);
// mediaPlayer.setSurface(surfaceHolder.getSurface());
try {
(prep) (mediaPlayer);
mediaPlayer. IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e) {
// TODO Auto-generated catch block
“() br> StackTrace(); br> e.print }
MediaPlayer.start();
}
4: After the playback is complete, release the mediaplayer and destroy the surface. Destroying the surface needs to make the surfaceview invisible:
@Override
Public void onCompletion(MediaPlayer mp) {
If(mediaPlayer!=null){
MediaPlayer.setDisplay(null);
MediaPlayer.reset(); mediaPlayer.reset(); mediaPlayer.reset();
mediaPlayer = null;
hs_surface.setVisibility(View.GONE);
This will call surfaceDestroyed, see below:
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(“surfaceDestroyed”, “surfaceDestroyed”);
surfaceHolder = null;
5: Repeat to play other videos. At this time, you need to create a mediaplayer and create a surfaceholder. Repeat the steps 1, 2, 3, and 4.
< /p>
See the entire code below:
p>
public class MediaPlayerService extends Service implements SurfaceHolder.Callback, OnCompletionListener {/** * Currently supports mixed video and picture, picture The duration of each picture is 8 seconds. * Loop playback. Video playback supports MediaPlayer and videoView. Currently, MediaPlayer is used. * */ private RelativeLayout home_sleep; private SurfaceView hs_surface; private ImageView hs_image; private SurfaceHolder surfaceHolder; private String TAG = MediaPlayerService.class.getSimpleName(); private int mShowImageTime = 8000; // private String path; // store the final playback location private int lastplay = 0; // multimedia playlist private ArrayListmedialist; private MediaPlayer mediaPlayer; private WindowManager windowManager; /** * Whether to addview flag */ private boolean addViewFlag = false; private WindowManager.LayoutParams mLayoutParams; private RelativeLayout hs_main; @Override public void onCreate() {super.onCreate(); medialist = new ArrayList (); windowManager = (WindowManager) get SystemService(Context.WINDOW_SERVICE); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); home_sleep = (RelativeLayout) inflater.inflate(R.layout.home_sleep, null); home_sleep.setOnTouchListener(new OnTouchListener() {@Override public boolean onTouch(View v, MotionEvent event) {if (addViewFlag) {windowManager.removeView(home_sleep); addViewFlag = false;// if (videoView.isPlaying()) {// videoView.stopPlayback();//} if( mediaPlayer.isPlaying()){ mediaPlayer.stop(); mediaPlayer.setDisplay(null); mediaPlayer.reset(); mediaPlayer.release(); mediaPlayer=null;}} return false;} }); hs_surface = (SurfaceView) home_sleep.findViewById(R.id.hs_surface); hs_image=(ImageView) home_sleep.findViewById(R.id.hs_image); hs_surface.setOnTouchListener(new OnTouchListener() {@Override public boolean onTouch(View v, MotionEvent event) {if (addViewFlag) {windowM anager.removeView(home_sleep); addViewFlag = false;// if (videoView.isPlaying()) {// videoView.stopPlayback();//} if(mediaPlayer.isPlaying()){ mediaPlayer.stop(); mediaPlayer. setDisplay(null); mediaPlayer.reset(); mediaPlayer.release(); mediaPlayer=null;}} return false;} }); videoView = (VideoView) home_sleep.findViewById(R.id.videoview); hs_main=(RelativeLayout ) home_sleep.findViewById(R.id.hs_main); mLayoutParams = new WindowManager.LayoutParams(); mLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE; mLayoutParams.alpha= (float)1.0; // Set the image format, the effect is transparent background mLayoutParams.format = PixelFormat.RGBA_8888; // Set the floating window to be non-focusable (implement the operation of other visible windows except the floating window) mLayoutParams.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN; // Adjust the docking position of the floating window display to the left Side top mLayoutParams.gravity = Gravity.BOTTOM; // Set the length and width data of the floating window mLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; mLayoutParams.height = 731; mLayoutParams.x = 0; mLayoutParams .y = 80;} VideoView videoView; @Override public int onStartCommand(Intent intent, int flags, int startId) {if (intent != null) {String action = intent.getStringExtra("action"); Log.v(" action", action+":" + medialist+":"+ medialist.size()); if(!isTopActivy("com.rqst.RqstQueue.HomeActivity", this)){ return 0;} if (action.equals(" show")) {if (addViewFlag) {return 0;} medialist = intent.getStringArrayListExtra("path"); if (medialist == null || medialist.size() == 0) {return 0; }else{ for (int i = 0; i play--------path:" + path); if (path != null && path.length() != 0) {if ((Utils.isvideo(path))) {// RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(1080,731);/ / videoView.setLayoutParams(params);// videoView.setVideoPath(path); // videoView.setMediaController(null); // videoView.setOnCompletionListener(new OnCompletionListener() {// // @Override// public void onCompletion(MediaPlayer mp) {// // TODO Auto-generated method stub// String deletedItem = null;// int size = medialist.size();// if (medialist != null && size != 0// && Utils.isok (medialist.get(0))) {// deletedItem = medialist.remove(0);// }// //TODO is deleted and added again, just reverse the order // if (deletedItem != null) {// medialist.add(size-1, deletedItem);// }// play(medialist.get(0));// }// });// videoView.re questFocus(); // videoView.start();// videoView.setVisibility(View.VISIBLE); if(mediaPlayer==null){ mediaPlayer = new MediaPlayer();} mediaPlayer.setOnCompletionListener(this); try {mediaPlayer. setDataSource(path); //Move} catch (Exception e) {e.printStackTrace(); if (addViewFlag) {windowManager.removeView(home_sleep); addViewFlag = false;}} hs_surface.setVisibility(View.VISIBLE); surfaceHolder = hs_surface.getHolder(); surfaceHolder.addCallback(this);} else if (Utils.ispic(path)) {hs_image.setVisibility(View.VISIBLE); Bitmap b = BitmapFactory.decodeFile(path); hs_image.setImageBitmap(b) ; hs_surface.setVisibility(View.GONE); picShowHandler.sendEmptyMessageDelayed(0, mShowImageTime);// videoView.setVisibility(View.INVISIBLE);} )else{ //This situation should not happen medialist.remove(0); play(medialist.get(0));}} private Handler picShowHandler = new Handler() {public void handleMessage(android.os.Message msg) {if (msg.what == 0) {String deletedItem = null; int size = medialist.size(); if (medialist != null && size != 0) {deletedItem = medialist .remove(0);} //TODO is deleted and added again, just reverse the order if (deletedItem != null) {medialist.add(size-1, deletedItem);} play(medialist.get(0));} }; }; @Override public IBinder onBind(Intent intent) {return null;} @Override public void surfaceCreated(SurfaceHolder holder) {Log.v("surfaceCreated", "surfaceCreated"); surfaceHolder = holder; mediaPlayer.setDisplay(holder );// mediaPlayer.setSurface(surfaceHolder.getSurface()); try {mediaPlayer.prepare();} catch (IllegalStateException e) {// TODO Auto-generated catch block e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch block e.printStackTrace();} if (lastplay runningTaskInfos = manager .getRunningTasks(Integer.MAX_VALUE); String cmpNameTemp = null; if (null != runningTaskInfos) {cmpNameTemp = (runningTaskInfos.get(0).topActivity).getClassName();} if (null == cmpNameTemp) {return false;} return cmpNameTemp.equals(cmdName); })