1. Create a project ServiceDemo01, layout two buttons in main activity: Start service and stop service.
2. Create a new service class: Playmusicservice
1 ackage com.hsiehway.servicedemo01;2 3 ImportAndroid.app.Service;4 Importandroid.content.Intent;5 ImportAndroid.media.MediaPlayer;6 ImportAndroid.os.IBinder;7 8 Public classPlaymusicserviceextendsService {9 Ten PrivateMediaPlayer Mmediaplayer; One A PublicPlaymusicservice () { - } - the @Override - Publicibinder onbind (Intent Intent) { - //Todo:return The communication channel to the service. - Throw NewUnsupportedoperationexception ("not yet implemented"); + } - + @Override A Public intOnstartcommand (Intent Intent,intFlagsintStartid) { atSystem.out.println ("Service Start"); -Mmediaplayer = Mediaplayer.create ( This, R.raw.gem);//Gem.mp3 - Mmediaplayer.start (); - return Super. Onstartcommand (Intent, flags, startid); - } - in @Override - Public voidOnDestroy () { toSystem.out.println ("Service Stop"); + Super. OnDestroy (); - mmediaplayer.stop (); the } *}
Code in the 3.MainActivity class
1 Packagecom.hsiehway.servicedemo01;2 3 Importandroid.content.Intent;4 Importandroid.support.v7.app.AppCompatActivity;5 ImportAndroid.os.Bundle;6 ImportAndroid.view.View;7 ImportAndroid.widget.Button;8 9 Public classMainactivityextendsappcompatactivity {Ten One PrivateButton startbtn,stopbtn; A - @Override - protected voidonCreate (Bundle savedinstancestate) { the Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); - -STARTBTN =(Button) Findviewbyid (R.ID.STARTBTN); +STOPBTN =(Button) Findviewbyid (R.ID.STOPBTN); - +Startbtn.setonclicklistener (NewStartlistener ()); AStopbtn.setonclicklistener (NewStoplistener ()); at } - - classStartlistenerImplementsview.onclicklistener{ - @Override - Public voidOnClick (view view) { -Intent Intent =NewIntent (mainactivity. This, Playmusicservice.class); in StartService (intent); - to } + } - the classStoplistenerImplementsview.onclicklistener{ * @Override $ Public voidOnClick (view view) {Panax NotoginsengIntent Intent =NewIntent (mainactivity. This, Playmusicservice.class); - StopService (intent); the + } A } the}
4. Run the interface
Service learning of Android four components