首先定义接口
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;@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.return new MusicBinder();}class MusicBinder extends Binder implements PlayInterface{@Overridepublic void play() {// TODO Auto-generated method stubPlayService.this.play();}@Overridepublic void playContiue() {// TODO Auto-generated method stubPlayService.this.playContiue();}@Overridepublic void pause() {// TODO Auto-generated method stubPlayService.this.pause();}}@Overridepublic 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;@Overrideprotected 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() {@Overridepublic void onClick(View arg0) {p.play();}});findViewById(R.id.contiue).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {p.playContiue();}});findViewById(R.id.pause).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stub
p.pause();}});}class Conn implements ServiceConnection{@Overridepublic void onServiceConnected(ComponentName arg0, IBinder arg1) {// TODO Auto-generated method stubp = (PlayInterface) arg1;}@Overridepublic void onServiceDisconnected(ComponentName arg0) {// TODO Auto-generated method stub
}}}