首先定义接口
package com.example.musicplay;public interface PlayInterface { void play(); void playContiue(); void pause();}
package com.example.musicplay;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.Binder;import android.os.IBinder;public class PlayService extends Service { private MediaPlayer mediaPlayer; @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return new MusicBinder(); } class MusicBinder extends Binder implements PlayInterface{ @Override public void play() { // TODO Auto-generated method stub PlayService.this.play(); } @Override public void playContiue() { // TODO Auto-generated method stub PlayService.this.playContiue(); } @Override public void pause() { // TODO Auto-generated method stub PlayService.this.pause(); } } @Override public void onCreate() { mediaPlayer = new MediaPlayer(); } private void play(){ //重置 mediaPlayer.reset(); try { mediaPlayer.setDataSource("sdcard/Charlotte Perrelli - Hero.mp3"); //准备 mediaPlayer.prepare(); } catch (Exception e) { // TODO Auto-generated catcssh block e.printStackTrace(); } mediaPlayer.start(); } private void playContiue(){ mediaPlayer.start(); } private void pause(){ mediaPlayer.pause(); }}
package com.example.musicplay;import android.os.Bundle;import android.os.IBinder;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;public class MainActivity extends Activity { private PlayInterface p; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(this,PlayService.class); startService(intent); bindService(intent, new Conn(), BIND_AUTO_CREATE); findViewById(R.id.paly).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { p.play(); } }); findViewById(R.id.contiue).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { p.playContiue(); } }); findViewById(R.id.pause).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub p.pause(); } }); } class Conn implements ServiceConnection{ @Override public void onServiceConnected(ComponentName arg0, IBinder arg1) { // TODO Auto-generated method stub p = (PlayInterface) arg1; } @Override public void onServiceDisconnected(ComponentName arg0) { // TODO Auto-generated method stub } }}