Two-way communication between Android service and Activity

Source: Internet
Author: User
 

The example of playing a music player a few days ago involves the interaction between the service and activity in the process of doing so. As a result, I just collected examples online. there are indeed many examples, however, there are few examples of mutual interaction between them. As a result, I decided to write down my example and share it with you. If you have any shortcomings, please give me some advice. (This is my first blog post on csdn. Thank you for your support)

The aidl technology must be used for communication between services and activities. It is not specific about the service. The example is more intuitive.

(1) Service aidl file: file name imusicservice. aidl

Package COM. carsmart. music. aidl; // reference the aidl (activity side) Import COM. carsmart. music. aidl. listener; interface imusicservice {void addlisener (in container PSC); void play (string musplaylistname, int musicindex); void playbydegree (INT degree); void pause (); void stop (); void next (); void previous (); void setplaypattern (INT playpattern); int getprogress (); int getduration (); string getplaylistname (); int getmusicindex ();}

 

(2) It is necessary to inherit imusicservice. Stub class in the Service (this class is the imusicservice. Java class generated automatically in the project's Gen folder if it is correct after the aidl file is written)

// Return to the Client
Public ibinder onbind (intent) {// todo auto-generated method stubplayerproxy = new musicplayerproxy (); Return playerproxy;} // implement the imusicservice. Stub subclass
private class MusicPlayerProxy extends IMusicService.Stub{@Overridepublic void addLisener(IPlayStatusChangeListener psc)throws RemoteException {// TODO Auto-generated method stubmusicPlayer.addLisener(psc);}@Overridepublic void play(String musPlayListName, int musicIndex) throws RemoteException {// TODO Auto-generated method stubmusicPlayer.play(musPlayListName,musicIndex);}@Overridepublic void playByDegree(int degree) throws RemoteException {// TODO Auto-generated method stubmusicPlayer.playByDegree(degree);}@Overridepublic void pause() throws RemoteException {// TODO Auto-generated method stubmusicPlayer.pause();}@Overridepublic void stop() throws RemoteException {// TODO Auto-generated method stubmusicPlayer.stop();}@Overridepublic void next() throws RemoteException {// TODO Auto-generated method stubmusicPlayer.next();}@Overridepublic void previous() throws RemoteException {// TODO Auto-generated method stubmusicPlayer.previous();}@Overridepublic void setPlayPattern(int playPattern) throws RemoteException {// TODO Auto-generated method stubmusicPlayer.setPlayPattern(playPattern);}@Overridepublic int getProgress() throws RemoteException {// TODO Auto-generated method stubreturn musicPlayer.getProgress();}@Overridepublic int getDuration() throws RemoteException {// TODO Auto-generated method stubreturn musicPlayer.getDuration();}@Overridepublic String getPlayListName() throws RemoteException {// TODO Auto-generated method stubreturn musicPlayer.getPlayListName();}@Overridepublic int getMusicIndex() throws RemoteException {// TODO Auto-generated method stubreturn musicPlayer.getMusicIndex();}}

(3) aidl file on the activity side: the file name iplaystatuschangelistener. The role of aidl in my example is to listen to the status of playing music and Song-related information.

Package com. carsmart. Music. aidl; // only basic data and string data can be transmitted. To transmit complex data or custom data, you must implement serializable or parcelable interfaces for the passed object.
         interface IPlayStatusChangeListener {                  void onPlayStatChange(int status);                 void onMusicInfoChange(String title,String artist);                 void onPlayMusicIndexChanged(String playListName,int musicIndex);          } 

(4) Implement iplaystatuschangelistener. stub on the activity side

Public class playstatuschangeadapter extends iplaystatuschangelistener. stub {// The playing status changes @ override public void onplaystatchange (INT status) throws RemoteException {// todo auto-generated method stub} // when the playing song changes, send the name of the currently played song to the playback interface @ override public void onmusicinfochange (String title, string artist) throws RemoteException {// todo auto-generated method stub} // when the playing song changes, broadcast the playlist name and index, used to merge the new playlist @ override public void onplaymusicindexchanged (string playlistname, int musicindex) throws RemoteException {// todo auto-generated method stub }}

(5) generate a serviceconnection subclass on the activity side for bindservice to connect to the server

 

Private class serconn implements serviceconnection {@ overridepublic void onserviceconnected (componentname name, ibinder Service) {// todo auto-generated method stubims = imusicservice. stub. asinterface (service); try {// if it is set in the constructor or oncreate method, a null pointer error may be reported (because IMS may not be connected) when setting the listener if (plastachalistener! = NULL) {IMS. addlisener (plastachalistener) ;}} catch (RemoteException e) {e. printstacktrace () ;}@ overridepublic void onservicedisconnected (componentname name) {// todo auto-generated method stubims = NULL ;}}

(6) The last step is also the easiest step to connect to the server.

        
        
        SerConn conn = new SerConn();
        Intent service = new Intent("com.carsmart.music.aidl.IMusicService");        this.bindService(service, conn, this.activity.BIND_AUTO_CREATE);

I hope you can give me more advice.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.