Android aidl and Remote service Invoke sample code _android

Source: Internet
Author: User
Tags stub

Android:aidl and remote service calls

The content of this talk, understand is difficult, perhaps you read a lot of material also can not see, but use up lack of simple deadly. So we simply take a music player in the progress bar example to illustrate the value of aidl and remote service and how to use, you put this example run side, experience is OK. The following example is my

Part of the project instance being prepared.

First of all, to explain the problems we face, if you do not understand the following description, please look at the previous course:

First, we know that in Android, if you need to play music, the most way is to use the MediaPlayer object, if we control the MediaPlayer object play in the activity, then once you open another program such as a browser, Then the song will stop immediately, which of course is not the result we need. What we need is to be able to listen to the music in the background while doing other things, so we need to put the operation of the MediaPlayer object in the background service.

Second, we have transferred the operation of the MediaPlayer to the service, in accordance with our previous practice, we send a intent object in the activity to the service object, in the intent transmission play Ah, Pause AH a kind of information to the service, so the service will know what to do. It all looks beautiful, but now there's a new problem, which is that I want to display a progress bar in the activity that follows the progress of the song in the MediaPlayer of the service, and if I click on a position in the progress bar, Also want to let the song jump to a new point of time to continue playing, this, how to achieve?

Third, we need to manipulate the MediaPlayer objects in the service in the activity as if the object were our own. We can use the Android Interface Definition language aidl (Android Interface definition Language) technology:

1, the service for the operation of MediaPlayer packaging into an interface (. aidl file)
2, in the service to build a subclass to implement this interface stub (stub) object
3, and returns this stub object in the Onbind () method.
4, the use of binding services in the activity to connect service, but not intent to convey information, but in the Serviceconnection onserviceconnected method, Gets the client use proxy for the stub object in the service. By manipulating the agents in the activity, we can achieve the purpose of manipulating the MediaPlayer object in the service. So we can want to use the same as local objects in the service, then the requirements of the progress bar will naturally be solved.

The following examples are not specifically prepared for this, so some extraneous code, and no comments, please forgive (this example is a complete explanation will be placed in the project training, are preparing):

1, a new project App_elfplayer, start activity is a splash screen:coveractivity

2, the contents of theAndroidmanifest.xml are as follows:

 <?xml version= "1.0" encoding= "Utf-8"?> <manifest package= "App.android.elfplayer"
  Xmlns:android= "Http://schemas.android.com/apk/res/android" android:versioncode= "1" android:versionname= "1.0" > <uses-sdk= "" "android:minsdkversion=" 7 "> <uses-permission=" "Android:name=" android.permission.WRITE_ External_storage "></uses> <application android:label=" @string/app_name "android:icon=" @drawable/icon " > <activity android:name= ".
        Coveractivity "> <intent-filter=" "> <action android:name=" Android.intent.action.MAIN ">
    <category android:name= "Android.intent.category.LAUNCHER" > </category></action></intent> </activity> <activity android:name= ". Playeractivity "> </activity> <service android:name=". Musicservice "android:enabled=" true "> </service> </application> </uses></manifest>

We note that there are 2 activity,1 service, as well as read and write permission declarations for external storage 3, Coveractivity.java code as follows: This is a full-screen splash screen, 2 seconds will jump to playeractivity

 package app.android.elfplayer;
Import android.app.Activity;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.view.Window;

Import Android.view.WindowManager; The public class Coveractivity extends activity {/** called ' when the ' activity is ' is a-created./@Override public Voi
    D onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    Requestwindowfeature (Window.feature_no_title);

    Setcontentview (R.layout.cover); New Handler (). postdelayed (New Runnable () {@Override public void run () {Intent mainintent = new Intent (Co
      Veractivity.this,playeractivity.class);
      CoverActivity.this.startActivity (mainintent);
     CoverActivity.this.finish ();

  }, 2000); }
}

The code for

4, Playeractivity.java is as follows:

Package app.android.elfplayer;
Import android.app.Activity;
Import Android.content.ComponentName;
Import Android.content.Context;
Import android.content.Intent;
Import android.content.ServiceConnection;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.IBinder;
Import Android.os.Message;
Import android.os.RemoteException;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.ImageButton;
Import Android.widget.SeekBar;

Import Android.widget.SeekBar.OnSeekBarChangeListener;
  public class Playeractivity extends activity {public static final int play = 1;

  public static final int PAUSE = 2;
  ImageButton Imagebuttonfavorite;
  ImageButton Imagebuttonnext;
  ImageButton Imagebuttonplay;
  ImageButton Imagebuttonpre;
  ImageButton imagebuttonrepeat;

  SeekBar Musicseekbar;
  Iserviceplayer IPlayer;
  Boolean isplaying = false;  

  Boolean isloop = false; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (SavediNstancestate);

    Setcontentview (R.layout.player);
    Imagebuttonfavorite = (ImageButton) Findviewbyid (r.id.imagebuttonfavorite);
    Imagebuttonnext = (ImageButton) Findviewbyid (R.id.imagebuttonnext);
    Imagebuttonplay = (ImageButton) Findviewbyid (R.id.imagebuttonplay);
    Imagebuttonpre = (ImageButton) Findviewbyid (R.id.imagebuttonpre);
    Imagebuttonrepeat = (ImageButton) Findviewbyid (r.id.imagebuttonrepeat);

    Musicseekbar = (SeekBar) Findviewbyid (R.id.musicseekbar);
    Bindservice (New Intent (Playeractivity.this, Musicservice.class), Conn, context.bind_auto_create);

    StartService (New Intent (Playeractivity.this, Musicservice.class));
        Imagebuttonplay.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {

        LOG.I ("Yao", "Imagebuttonplay-> OnClick");
          if (!isplaying) {try {iplayer.play ();
          catch (RemoteException e) {e.printstacktrace ();
        }  Imagebuttonplay.setbackgroundresource (R.drawable.pause_button);

        IsPlaying = true;
          else {try {iplayer.pause ();
          catch (RemoteException e) {e.printstacktrace ();
          } imagebuttonplay.setbackgroundresource (R.drawable.play_button);
        IsPlaying = false;

    }
      }
    }); Musicseekbar.setonseekbarchangelistener (New Onseekbarchangelistener () {@Override public void Onprogresschang Ed (SeekBar SeekBar, int progress, Boolean fromuser) {} @Override public void Onstarttrackingtouch (seek Bar seekBar) {} @Override public void Onstoptrackingtouch (SeekBar seekBar) {if IPlayer!= nu
          ll) {try {Iplayer.seekto (seekbar.getprogress ());
          catch (RemoteException e) {e.printstacktrace ();

    }
        }
      }
    });
  Handler.post (Updatethread); Private Serviceconnection conn = NEW serviceconnection () {public void onserviceconnected (componentname className, IBinder service) {log.i ("Yao")
      "Serviceconnection-> onserviceconnected");
    IPlayer = IServicePlayer.Stub.asInterface (service);
  public void onservicedisconnected (ComponentName className) {};

  };
  Handler Handler = new Handler () {@Override public void Handlemessage (msg) {};

  };
        Private Runnable Updatethread = new Runnable () {@Override public void run () {if (IPlayer!= null) {
          try {Musicseekbar.setmax (iplayer.getduration ());
        Musicseekbar.setprogress (Iplayer.getcurrentposition ());
        catch (RemoteException e) {e.printstacktrace ();
    } handler.post (Updatethread);

}
  }; }

5, the use of the iserviceplayer.aidl, placed in the same package as the Java file, the contents are as follows:

Package app.android.elfplayer;
Interface iserviceplayer{
  void Play ();
  void Pause ();
  void Stop ();
  int getduration ();
  int GetCurrentPosition ();
  void Seekto (int current);
  Boolean Setloop (Boolean loop);
}

Once you have written this iserviceplayer.aidl file, ADT will automatically help you generate Iserviceplayer.java files in the Gen directory.

6, the contents of theMusicservice.java are as follows:

Package app.android.elfplayer;
Import Android.app.Service;
Import android.content.Intent;
Import Android.media.MediaPlayer;
Import Android.os.IBinder;
Import android.os.RemoteException;

Import Android.util.Log;

  public class Musicservice extends Service {String tag = "Yao";

  public static MediaPlayer MPlayer;

  public Boolean ispause = false;
      Iserviceplayer.stub Stub = new Iserviceplayer.stub () {@Override public void play () throws RemoteException {
    Mplayer.start ();
    @Override public void Pause () throws RemoteException {Mplayer.pause ();
    @Override public void Stop () throws RemoteException {mplayer.stop ();
    @Override public int getduration () throws RemoteException {return mplayer.getduration ();
    @Override public int getcurrentposition () throws RemoteException {return mplayer.getcurrentposition ();
@Override public void Seekto (int current) throws RemoteException {      Mplayer.seekto (current);
    @Override Public Boolean Setloop (Boolean loop) throws RemoteException {return false;

  }

  };
    @Override public void OnCreate () {LOG.I (tag, Musicservice onCreate ());
  MPlayer = Mediaplayer.create (Getapplicationcontext (), ELFPLAYERUTIL.GETFILEINSD ("Wind.mp3"));
  @Override public IBinder onbind (Intent Intent) {return stub; }

}

7, realize the effect chart:

Finally, Aidl provides a very simple way to expose objects or methods within a process to another program, as if another program had them.

The above is the Android Aidl and remote service introduction and simple application, follow-up continue to supplement the relevant knowledge, thank you for your support!

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.