Android note 34. Integrated Service instance 2, android. service
Integrated instance 2: client access to remote ServiceImplementation: Use a button to obtain the status of the remote Service and display it in two text boxes. Idea: Assume that application A needs to communicate with application B and call the getName () and getAuthor () methods in application B. Application B provides services to application A in Service mode. Therefore, we can regard application A as A client, and application B as A server, respectively named AILDClient and AILDServer.
1. Server Applications1. src/com. example. aildserver/song. aidl: AILD FileAfter the aidl file is created, select Save. eclipse automatically generates the Song. java interface file in the project's gen directory. The interface file generates a Stub abstract class, which includes methods defined by aidl and other auxiliary methods, such as geName () and getSong, we can use these two methods to read and write data from the client to the Service server.
- PackageCom. example. aildserver;
- InterfaceSong
- {
- String getName ();
- String getSong ();
- }
Location:
Note the following when writing Aidl files: 1. the Interface Name and aidl file name are the same; 2. you do not need to add access permission modifiers such as public and private before interfaces and methods, or use final or static; 3. the types supported by Aidl by default include the Basic java types (int, long, boolean, etc.) and (String, List, Map, and CharSequence). import Declaration is not required when these types are used. Element Types in List and Map must be supported by Aidl. If you use a custom type as a parameter or return value, the custom type must implement the Parcelable interface. 4. The custom type and other Interface Types generated by AIDL should be explicitly imported in the aidl description file, even if the class and the defined package are in the same package. 5. All non-Java basic type parameters in the aidl file must be marked with in, out, And inout to indicate whether the parameters are input parameters, output parameters, or input and output parameters. 6. The default mark of the original Java type is in, and cannot be any other mark.
2. src/com. example. aildserver/MyService. javaFunction: sub-class of the Service to complete the core steps of Service Development: (1) rewrite the onBind () method of the Service (used to return an IBinder object), onCreate () method, onDestroy () method, onUnbind () method; (2) defines a Stub subclass. The internal class implements the IBinder and Song interfaces. The subclass object will act as the onBind () of the remote Service () method returns the second parameter of the onServiceConnected method that the proxy of the IBinder object transmits to the ServiceConnection of the client.
- Package com. example. aildserver;
- Import com. example. aildserver. Song. Stub;
- Import android. app. Service;
- Import android. content. Intent;
- Import android. OS. Binder;
- Import android. OS. IBinder;
- Import android. OS. RemoteException;
- Public class MyService extends Service {
- Private String [] names = new String [] {"Lin Junjie", "Cai Yilin", "Deng Ziqi "};
- Private String [] songs = new String [] {"unfortunately not if", "third person", "many distant places must be together "};
- Private String name, song;
- Private int current = 1; // current location
- Private MyBinder binder = new MyBinder (); // instantiate an IBinder object
- /* 0. Stub internal class
- * This internal class implements the IBinder and Song interfaces. This Stub class will be used as the callback class of the remote Service. */
- Public class MyBinder extends Stub
- {
- // A. The client calls back this method to obtain the artist name
- Public String getName () throws RemoteException
- {
- Return name;
- }
- // B. The client calls back this method to obtain the song
- Public String getSong () throws RemoteException
- {
- Return song;
- }
- }
- /* 1. onBind Method
- * The service is used to return an IBinder object to the client for convenient communication.
- */
- @ Override
- Public IBinder onBind (Intent arg0 ){
- Return binder;
- }
- /* 2. onCreate Method
- * This method is automatically called after the Service is started for initialization.
- **/
- Public void onCreate (){
- Name = names [current]; // assign values to name and song
- Song = songs [current];
- System. out. println ("Service print: name =" + name + "song =" + song );
- Super. onCreate ();
- }
- /* 3. onDestroy Method
- * When a visitor calls the Context. stopService method, call this method to disable the Service.
- **/
- Public void onDestroy (){
- Super. onDestroy ();
- }
- /* 4. onUnbind Method
- * When a visitor calls the Context. unBind () method, call this method to unBind it from the Service */
- Public boolean onUnbind (Intent intent ){
- Return false;
- }
- }
Note 1: When the client accesses the Service, Android does not directly return the Service object to the client. The Service only calls back a callback object (IBinder object) to the client through the onBind () method. NOTE 2: Unlike binding a local Service, the onBind () method of the local Service directly transmits the IBinder object to the second parameter of the onServiceConnected method of ServiceConnection on the client. However, the onBind () method of the remote Service only transmits the proxy of the IBinder object to the second parameter of the onserviceconnection onServiceConnected method of the client. After the client obtains the proxy of the remote Service's IBinder object, it can call back the attributes or methods of the remote Service through the IBinder object.
3. AndroidManifest. xmlFunction: configure the Service component and specify its action attribute to facilitate other applications to start the Service)
- <Application
- ........
- <! -- Configure service -->
- <Service android: name = ". MyService">
- <Intent-filter>
- <Action android: name = "com. jiangdongguo. service"/>
- </Intent-filter>
- </Service>
- </Application>
2. Client Applications
1. Copy the server. aidl file to the client.Copy the package of the aidl file in the AIDLService application together with the aidl file to the client AIDLClient application. eclipse automatically generates A Song for the aidl file in the gen directory of application. java interface file. Then, you can communicate with the AIDLService application in the AIDLClient application. 2. src/com. example. aildclient/MainActivity. java function: (1) Start the Server Service; (2) obtain the returned IBinder proxy object and complete communication with the server program.
- Package com. example. aildclient;
- Import com. example. aildserver. Song;
- Import android. app. Activity;
- Import android. app. Service;
- Import android. content. ComponentName;
- Import android. content. Intent;
- Import android. content. ServiceConnection;
- Import android. OS. Bundle;
- Import android. OS. IBinder;
- Import android. OS. RemoteException;
- Import android. view. View;
- Import android. view. View. OnClickListener;
- Import android. widget. Button;
- Import android. widget. EditText;
- Public class MainActivity extends Activity {
- Private Button getBtn;
- Private EditText song;
- Private EditText name;
- Private Song binder;
- // 1. Create a ServiceConnection object
- Private ServiceConnection conn = new ServiceConnection ()
- {
- Public void onServiceConnected (ComponentName name, IBinder service)
- {
- Binder = Song. Stub. asInterface (service); // gets the proxy IBinder object returned by the Service
- }
- Public void onServiceDisconnected (ComponentName name ){
- }
- };
- Protected void onCreate (Bundle savedInstanceState ){
- Super. onCreate (savedInstanceState );
- SetContentView (R. layout. main );
- GetBtn = (Button) findViewById (R. id. get );
- Song = (EditText) findViewById (R. id. song );
- Name = (EditText) findViewById (R. id. name );
- // 2. Specify the Service to be started
- Intent intent = new Intent ("com. jiangdongguo. service ");
- BindService (intent, conn, Service. BIND_AUTO_CREATE );
- GetBtn. setOnClickListener (new OnClickListener (){
- Public void onClick (View arg0)
- {
- Try {
- Name. setText (binder. getName ());
- Song. setText (binder. getSong ());
- } Catch (RemoteException e ){
- E. printStackTrace ();
- }
- }
- });
- }
- }
For remote service calls, the object that the remote service returns to the client is a proxy object. When the client references this object in the onServiceConnected (ComponentName, IBinder service) method, it cannot directly convert it to an interface-type instance, instead, use asInterface (IBinder iBinder) for type conversion.
Iii. effect demonstration