Surface libraries in Android development and examples of using them to make the player UI _android

Source: Internet
Author: User

1, Surface
1.1, as in C language programming, through a file handle, you can manipulate the file, get the contents of the file. Similarly, the contents of raw buffer can be obtained by surface. Native buffers (raw buffer) store the pixel data for the current window.

1.2, in fact, when you get a surface object, you get a canvas (canvas) object. This can be seen by looking at the \frameworks\base\core\java\android\view\surface.java file to know that the Surface class defines a canvas member variable

private int msurfacecontrol; 
private int msavecount; 
Private Canvas Mcanvas; 
private int mnativesurface; 
private int msurfacegenerationid; 
Private String Mname; 

1.3, understand the canvas object, you can use it as a canvas, canvas most of the method is to set the size of the canvas, shape, canvas background color, and so on, to draw on the canvas, the general to use with paint objects, as the name suggests, paint is the style of the brush, pigment color and so

Create a brush  
Paint Paint = new Paint ();  
Paint.setcolor (color.red)//Set red  
 
canvas.drawcircle (all, paint);/Draw a circle  

1.4, the function of surface itself is similar to a handle, get the handle can get the canvas, the primary buffer and other aspects of the content.

1.5, Surface implements the Parcelable interface (implements Parcelable), which means that the surface object can write the data that is displayed to the Parcel and can read the data back from the Parcel.

The

2, Surfaceview
Surfaceview provides a surface specifically for drawing, which is embedded in the surface. You can control the format and size of this surface. Surfaceview controls the correct drawing position of this surface on the screen. The
surface is z-ordered (that is, in the XYZ coordinate system, the z-valued surface is covered above the small Z-value surface), indicating that it is always behind its own window. Surfaceview provides a visible area for surface in the display window to see the contents of the surface. Some overlay layers (overlays) can be placed above surface, such as button, TextView, and so on. However, it should be noted that if the surface has a fully transparent control, then with each change in the surface, these fully transparent controls will be rendered again, which will affect the performance and display effect.
You can access surface by Surfaceholder this interface, while executing the Getholder () method can get Surfaceholder interface.
When a surfaceview window is visible, the surface is created and surface is destroyed when the Surfaceview window is hidden. Of course, you can also use the replication surfacecreated (Surfaceholder) and surfacedestroyed (Surfaceholder)   both to verify when surface is created and when it is destroyed.
Surfaceview provides a surface that runs on a rendering thread, and if you want to update the screen, you need to understand the process knowledge.
All Surfaceview and Surfaceholder.callback methods should be called within the main thread (UI thread) and should ensure the synchronization of the variables accessed by the rendering process.
You must make sure that only when the surface is valid (i.e. when the surface life cycle is SurfaceHolder.Callback.surfaceCreated () and SurfaceHolder.Callback.surfaceDestroyed () in order for the render process to be accessible.

2.1, Surfaceview and surface contact
In simple terms, the Surfaceview-surface connection is that surface is the data that manages the display (implementsparcelable), including the exchange that is stored in the data. And Surfaceview is showing the data to the screen.
The links are as shown in the picture:

3, Surfaceholder
Surfaceholder is an abstract interface that controls surface, you can control surface size and format by Surfaceholder, or modify surface pixels, monitor surface changes, and so on, Surfaceholder is a typical interface for Surfaceview.
Unlike direct control Surfaceview to modify surface, you need to be aware of Lockcanvas () and callback.surfacecreated () when using Surfaceholder to modify surface. These two methods.
Surfaceholder several methods used to control the surface process.

3.1. Abstract void Addcallback (Surfaceholder.callback Callback)
Give Surfaceholder a callback object.

3.2. Abstract Canvas Lockcanvas (Rect dirty)
Lock one area of the canvas and return the Canvas object canvas (when there is only one area of the updated content, while pursuing efficiency, you can only
New part of the area without having to update all canvas areas

3.3. Abstract Canvas Lockcanvas ()
Locks the canvas, returns the Canvas object canvas

3.4. Abstract void Removecallback (Surfaceholder.callback Callback)
To remove a callback object

3.5. Abstract void Unlockcanvasandpost (Canvas Canvas)
End the lock drawing and submit the change.

4, Surfaceholder.callback
Surfaceholder.callback is an interface for monitoring surface changes.

4.1. Public abstract voidsurfacechanged (surfaceholder holder, int format, int width, int height)
Surface is called when a change occurs

4.2. Public abstract voidsurfacecreated (Surfaceholder holder)
Called when surface is created, the thread that renders the screen is typically opened in this method.

4.3. Public abstract voidsurfacedestroyed (Surfaceholder holder)
is called when it is destroyed, and typically the rendered thread is stopped in this method.

Attach the above mentioned several contact methods

Surfaceholder = Surfaceview.getholder (); 
 
Surface = Surfaceholder.getsurface (); 
 
Canvas =surfaceholder.lockcanvas (Rect dirty) 
 
Canvas =surface.lockcanvas  (Rect dirty) 

5, DEMO: Through Surfaceview and surfaceholder for video playback
use Audioview for video playback, is not very uncomfortable, stereotyped mode, nausea bar. Here, we can wrap the MediaPlayer in some way. And what is used is Surfaceview and Surfaceholder.
Final Effect Diagram:

We offer four buttons to play control.

Layout file Media.xml code:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical " > <surfaceview android:id= "@+id/surfaceview1" android:layout_width= "320px" android:layout_height= "160px" > 
  </SurfaceView> <linearlayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:orientation= "Horizontal" > <imagebutton android:id= "@+id/button_play" android:src= "@drawable/play" an droid:onclick= "ButtonClick" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" ></ imagebutton> <imagebutton android:id= "@+id/button_pause android:src=" @drawable/pause "android:onClick=" ButtonClick "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "></ImageButton> ImageButton android:id= "@+id/button_stop" android:src= "@drawabLe/stop "android:onclick=" ButtonClick "android:layout_width=" wrap_content "android:layout_height=" Wrap_content " ></ImageButton> <imagebutton android:id= "@+id/button_reset" android:src= "@drawable/reset" Android:o nclick= "ButtonClick" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" ></ 

 Imagebutton> </LinearLayout> </LinearLayout>

Activity code:

Package Cn.com.chenzheng_java.media; 
Import android.app.Activity; 
Import Android.media.AudioManager; 
Import Android.media.MediaPlayer; 
Import Android.os.Bundle; 
Import Android.util.Log; 
Import Android.view.SurfaceHolder; 
Import Android.view.SurfaceView; 
Import Android.view.View;  /** * @description implement its own player via Surfaceview/surfaceholder * @author Chenzheng_java * @since 2011/03/23 * @description 
 In addition, we can use MediaPlayer to add Onpreparedlistener * and Oncompletionlistener events to control the playback and playback after the completion of the operation. * When using Surfaceview and Surfaceholder for video playback, the structure is this: * 1, first, we get a surfaceview * 2 from the layout file, through Surfaceview.getholder () method to obtain the Surfaceholder * 3 corresponding to the container, with some default settings for the Srufaceholder, such as Addcallback () and Settype () * 4, via Mediaplayer.setdisplay () method to link the video playback with the playback container/public class Mymediaplayeractivity extends the activity {MediaPlayer MediaPlayer;//Player internal implementation is through  MediaPlayer Surfaceview Surfaceview//In the video container Surfaceholder surfaceholder;//control Surfaceview Properties (dimensions, format, etc.) Object Boolean Ispause; Whether@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate) has been suspended; 
    Setcontentview (R.layout.media); 
    Surfaceview = (Surfaceview) Findviewbyid (R.ID.SURFACEVIEW1); 
    /** * Gets the surefaceholder * * Surfaceholder = Surfaceview.getholder () associated with the current Surfaceview. 
       
      /** * Registers the method that should be executed when the Surfaceview is created, changed, and destroyed * * Surfaceholder.addcallback (new Surfaceholder.callback () { 
        @Override public void surfacedestroyed (Surfaceholder holder) {LOG.I ("notification", "Surfaceholder was destroyed"); 
      if (mediaplayer!=null) mediaplayer.release (); @Override public void surfacecreated (Surfaceholder holder) {LOG.I ("notification", "Surfaceholder is C 
      Reate "); @Override public void surfacechanged (surfaceholder holder, int format, int width, int h 
      Eight) {log.i ("notice", "Surfaceholder changed"); 
     
    } 
    }); 
   /**  * Here must be set to Surfaceholder.surface_type_push_buffers oh, meaning * is to create a PUSH ' SURFACE ', the main feature is not to buffer * * * * Surfaceholde 
  R.settype (surfaceholder.surface_type_push_buffers);  /*** * @param Targetbutton button is clicked by the user * * public void ButtonClick (View targetbutton) {int ButtonID = 
    Targetbutton.getid (); 
      Switch (ButtonID) {case r.id.button_play:play (); 
    Break 
      Case R.id.button_pause:pause (); 
    Break 
      Case R.id.button_reset:reset (); 
    Break 
      Case R.id.button_stop:stop (); 
    Break 
    Default:break; 
    }/** * Playing/private void play () {mediaPlayer = new MediaPlayer (); 
     
    Set the multimedia stream type Mediaplayer.setaudiostreamtype (audiomanager.stream_music); 
    Set the container Mediaplayer.setdisplay (surfaceholder) for displaying the MediaPlayer; 
      try {mediaplayer.setdatasource ("/data/jinsha.3gp"); 
      Mediaplayer.prepare (); Mediaplayer.start (); 
    Ispause = false; 
    catch (Exception e) {log.i ("notification", "error occurred during playback"); 
    }/** * Suspend/private void pause () {LOG.I ("Notification", "Click the pause button"); 
      if (ispause==false) {mediaplayer.pause (); 
    Ispause=true; 
      }else{Mediaplayer.start (); 
    Ispause=false; 
    }/** * Reset */private void Reset () {log.i ("notice", "click Reset Button"); 
    Jump to the beginning of the video mediaplayer.seekto (0); 
  Mediaplayer.start (); 
    /** * Stop/private void Stop () {log.i ("notice", "Click the Stop button"); 
    Mediaplayer.stop (); 
     
  Mediaplayer.release (); 
 } 
   
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.