public class MyGridActivity extends Activity implements Callback,OnClickListener{ private static final String TAG = "MyGridActivity"; private Button btn1,btn2; SurfaceHolder holder; MediaPlayer mp; SurfaceView sv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.main04); btn1 = (Button) findViewById(R.id.play2_Button); btn2 = (Button) findViewById(R.id.pause2_Button); sv = (SurfaceView) findViewById(R.id.mysurfaceView1); holder = sv.getHolder(); holder.addCallback(this); holder.setFixedSize(320,240); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mp = new MediaPlayer(); btn1.setOnClickListener(this); btn2.setOnClickListener(this); } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder arg0) { // TODO Auto-generated method stub } @Override public void surfaceDestroyed(SurfaceHolder arg0) { // TODO Auto-generated method stub } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v.getId()==R.id.play2_Button){ mp.setDisplay(holder); try{ mp.setDataSource("/sdcard/movie.mp4"); mp.prepare(); }catch(Exception e){ Log.e(TAG, e.getMessage(), e); } mp.start(); }else if(v.getId()==R.id.pause2_Button){ mp.stop(); } } }
XML配置文件:
<?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/mysurfaceView1" android:layout_width="fill_parent" android:layout_height="200px" /> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > <Button android:id="@+id/play2_Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="播放" /> <Button android:id="@+id/pause2_Button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="暂停" /> </LinearLayout> </LinearLayout>