Musicservice.java Package com.zeph.android.service; Import Android.app.Service; Import android.content.Intent; Import Android.media.MediaPlayer; Import Android.os.IBinder; public class Musicservice extends Service { Private MediaPlayer Mmediaplayer; @Override Public IBinder Onbind (Intent arg0) { return null; } @Override public void OnCreate () { Super.oncreate (); Mmediaplayer = Mediaplayer.create (this, R.RAW.MUSIC01); } @Override public void OnDestroy () { Super.ondestroy (); Mmediaplayer.stop (); Mmediaplayer.release (); } @Override public void OnStart (Intent Intent, int startid) { super.onstart (Intent, Startid); int operate = Intent.getintextra ("Operate", 3); switch (operate) { case 0: if (!mmediaplayer.isplaying ()) { mmediaplayer.start (); } break; case 1: if (mmediaplayer.isplaying ()) { Mmediaplayer.pause (); } break; case 2: if (mmediaplayer.isplaying ()) { Mmediaplayer.stop (); mmediaplayer = Mediaplayer.create (this, R.RAW.MUSIC01); } break; default: break } Servicetestactivity.java Package com.zeph.android.service; Import android.app.Activity; Import android.content.Intent; Import Android.os.Bundle; Import Android.view.View; Import Android.view.View.OnClickListener; Import Android.widget.Button; public class Servicetestactivity extends activity { Private Button PlayButton; Private Button Pausebutton; Private Button Stopbutton; Private Button StopService; @Override public void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.main); PlayButton = (Button) Findviewbyid (R.id.playbutton); Pausebutton = (Button) Findviewbyid (R.id.pausebutton); Stopbutton = (Button) Findviewbyid (R.id.stopbutton); StopService = (Button) Findviewbyid (R.id.stopservice); Playbutton.setonclicklistener (New Buttononclicklistener ()); Pausebutton.setonclicklistener (New Buttononclicklistener ()); Stopbutton.setonclicklistener (New Buttononclicklistener ()); Stopservice.setonclicklistener (New Buttononclicklistener ()); } public class Buttononclicklistener implements Onclicklistener { @Override public void OnClick (view view) { Intent Intent = new Intent (); Intent.setclass (Getapplicationcontext (), musicservice.class); if (view = = PlayButton) { Intent.putextra ("operate", 0); StartService (Intent); else if (view = = Pausebutton) { Intent.putextra ("Operate", 1); StartService (Intent); else if (view = = Stopbutton) { Intent.putextra ("Operate", 2); StartService (Intent); else if (view = = StopService) { StopService (Intent); } } } } |