Android Music player
Using the Actiivity and service components to Android
Play Music using service components
Action buttons, etc. use activity to interact with the user
At the same time, in order to turn the service process into a service process, to prevent the activity from destroying while still executing the service, need to use service-initiated mixed calls, that is, using StartService (), and then use the Bindservice () method.
Principle: Use the Bindservice () method to start the service. Returns a IBinder object in the Onserviceconnected () method of serviceconnection that allows you to manipulate the way music is played in the music service.
Code:
Mainactivity
1 Importandroid.app.Activity;2 ImportAndroid.content.ComponentName;3 Importandroid.content.Intent;4 Importandroid.content.ServiceConnection;5 ImportAndroid.os.Bundle;6 ImportAndroid.os.IBinder;7 ImportAndroid.view.View;8 9 Public classMainactivityextendsActivity {Ten One PrivateMyserviceconnection Conn; A Privatemusicinterface mi; - - @Override the protected voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); - +Intent Intent =NewIntent ( This, Musicservice.class); - StartService (intent); +conn =Newmyserviceconnection ();
StartService (Intent); Turn the service process into a service process to prevent the activity from being destroyed and killed A Bindservice (Intent, Conn, bind_auto_create); at } - - classMyserviceconnectionImplementsserviceconnection { - - @Override - Public voidonserviceconnected (componentname name, IBinder service) { in //TODO auto-generated Method Stub -Mi =(musicinterface) service; to } + - @Override the Public voidonservicedisconnected (componentname name) { * //TODO auto-generated Method Stub $ Panax Notoginseng } - the } + A Public voidPlay (View v) { the Mi.play (); + - } $ $ Public voidPause (View v) { - mi.pause (); - } the}
Musicservice:
1 ImportAndroid.app.Service;2 Importandroid.content.Intent;3 ImportAndroid.os.Binder;4 ImportAndroid.os.IBinder;5 6 Public classMusicserviceextendsService {7 8 @Override9 Publicibinder onbind (Intent Intent) {Ten //TODO auto-generated Method Stub One return NewMusiccontrol (); A } - - classMusiccontrolextendsBinderImplementsMusicinterface { the Public voidPlay () { -Musicservice. This. Play (); - }; - + Public voidpause () { -Musicservice. This. Pause (); + } A } at - Public voidPlay () { -System.out.println ("Play Music"); - } - - Public voidpause () { inSystem.out.println ("Pause Music"); - } to +}
The Musiccontrol class is extracted as an interface so that only the methods of the interface can be accessed in the mainactivity, and the other methods in the Musiccontrol class are not used by the method
Musicinterface:
1 Public Interface musicinterface {2 3 Public void play (); 4 Public void pause (); 5 6 }
The implementation of the music player developed by Android