Android note 34. Integrated Service instance 2, android. service

Source: Internet
Author: User
Tags call back

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.

  1. PackageCom. example. aildserver;
  2. InterfaceSong
  3. {
  4. String getName ();
  5. String getSong ();
  6. }
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.
  1. Package com. example. aildserver;
  2. Import com. example. aildserver. Song. Stub;
  3. Import android. app. Service;
  4. Import android. content. Intent;
  5. Import android. OS. Binder;
  6. Import android. OS. IBinder;
  7. Import android. OS. RemoteException;
  8. Public class MyService extends Service {
  9. Private String [] names = new String [] {"Lin Junjie", "Cai Yilin", "Deng Ziqi "};
  10. Private String [] songs = new String [] {"unfortunately not if", "third person", "many distant places must be together "};
  11. Private String name, song;
  12. Private int current = 1; // current location
  13. Private MyBinder binder = new MyBinder (); // instantiate an IBinder object
  14. /* 0. Stub internal class
  15. * This internal class implements the IBinder and Song interfaces. This Stub class will be used as the callback class of the remote Service. */
  16. Public class MyBinder extends Stub
  17. {
  18. // A. The client calls back this method to obtain the artist name
  19. Public String getName () throws RemoteException
  20. {
  21. Return name;
  22. }
  23. // B. The client calls back this method to obtain the song
  24. Public String getSong () throws RemoteException
  25. {
  26. Return song;
  27. }
  28. }
  29. /* 1. onBind Method
  30. * The service is used to return an IBinder object to the client for convenient communication.
  31. */
  32. @ Override
  33. Public IBinder onBind (Intent arg0 ){
  34. Return binder;
  35. }
  36. /* 2. onCreate Method
  37. * This method is automatically called after the Service is started for initialization.
  38. **/
  39. Public void onCreate (){
  40. Name = names [current]; // assign values to name and song
  41. Song = songs [current];
  42. System. out. println ("Service print: name =" + name + "song =" + song );
  43. Super. onCreate ();
  44. }
  45. /* 3. onDestroy Method
  46. * When a visitor calls the Context. stopService method, call this method to disable the Service.
  47. **/
  48. Public void onDestroy (){
  49. Super. onDestroy ();
  50. }
  51. /* 4. onUnbind Method
  52. * When a visitor calls the Context. unBind () method, call this method to unBind it from the Service */
  53. Public boolean onUnbind (Intent intent ){
  54. Return false;
  55. }
  56. }
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)
  1. <Application
  2. ........
  3. <! -- Configure service -->
  4. <Service android: name = ". MyService">
  5. <Intent-filter>
  6. <Action android: name = "com. jiangdongguo. service"/>
  7. </Intent-filter>
  8. </Service>
  9. </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.
  1. Package com. example. aildclient;
  2. Import com. example. aildserver. Song;
  3. Import android. app. Activity;
  4. Import android. app. Service;
  5. Import android. content. ComponentName;
  6. Import android. content. Intent;
  7. Import android. content. ServiceConnection;
  8. Import android. OS. Bundle;
  9. Import android. OS. IBinder;
  10. Import android. OS. RemoteException;
  11. Import android. view. View;
  12. Import android. view. View. OnClickListener;
  13. Import android. widget. Button;
  14. Import android. widget. EditText;
  15. Public class MainActivity extends Activity {
  16. Private Button getBtn;
  17. Private EditText song;
  18. Private EditText name;
  19. Private Song binder;
  20. // 1. Create a ServiceConnection object
  21. Private ServiceConnection conn = new ServiceConnection ()
  22. {
  23. Public void onServiceConnected (ComponentName name, IBinder service)
  24. {
  25. Binder = Song. Stub. asInterface (service); // gets the proxy IBinder object returned by the Service
  26. }
  27. Public void onServiceDisconnected (ComponentName name ){
  28. }
  29. };
  30. Protected void onCreate (Bundle savedInstanceState ){
  31. Super. onCreate (savedInstanceState );
  32. SetContentView (R. layout. main );
  33. GetBtn = (Button) findViewById (R. id. get );
  34. Song = (EditText) findViewById (R. id. song );
  35. Name = (EditText) findViewById (R. id. name );
  36. // 2. Specify the Service to be started
  37. Intent intent = new Intent ("com. jiangdongguo. service ");
  38. BindService (intent, conn, Service. BIND_AUTO_CREATE );
  39. GetBtn. setOnClickListener (new OnClickListener (){
  40. Public void onClick (View arg0)
  41. {
  42. Try {
  43. Name. setText (binder. getName ());
  44. Song. setText (binder. getSong ());
  45. } Catch (RemoteException e ){
  46. E. printStackTrace ();
  47. }
  48. }
  49. });
  50. }
  51. }
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

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.