Activity and service communication (between different processes)

Source: Internet
Author: User

Use messenger

The preceding method can only be used in the same process. If you want to communicate with the service of another process, you can use messenger.

In fact, there is also aidl in the way of implementing IPC (inter-process communication), but it is recommended to use messenger, which has two advantages:

1. using messenger is much simpler than using aidl.

2. When using messenger, all messages sent from the activity will be placed in a queue and will not request services at the same time, so it is thread-safe. If yourProgramTo access the service through multiple threads, you can use aidl. Otherwise, it is best to use the messenger method.

However, in fact, the bottom layer of messenger is implemented by aidl. Let's take a look at the implementation method and first look at the service'sCode:

 

Java code
  1. Public ClassMessengerserviceExtendsService {
  2. /** Message type used in handler */
  3. Static Final IntMsg_say_hello =1;
  4. /** 
  5. * Handler used by the Service to process messages sent from an activity 
  6. */
  7. ClassIncominghandlerExtendsHandler {
  8. @ Override
  9. Public VoidHandlemessage (Message MSG ){
  10. Switch(Msg. What ){
  11. CaseMsg_say_hello:
  12. Toast. maketext (getapplicationcontext (),"Hello! ", Toast. length_short). Show ();
  13. Break;
  14. Default:
  15. Super. Handlemessage (MSG );
  16. }
  17. }
  18. }
  19. /** 
  20. * This messenger can be associated with the handler in the service. The activity uses this object to send a message to the service, and the service uses handler to process the message. 
  21. */
  22. FinalMessenger mmessenger =NewMessenger (NewIncominghandler ());
  23. /** 
  24. * When an activity is bound to a service, an ibinder is returned using this method. The activity uses the messenger created by this ibinder to communicate with the service handler. 
  25. */
  26. @ Override
  27. PublicIbinder onbind (intent ){
  28. Toast. maketext (getapplicationcontext (),"Binding", Toast. length_short). Show ();
  29. ReturnMmesder. getbinder ();
  30. }
  31. }

 

 Let's take a look at the activity code:

 

Java code
  1. Public ClassActivitymessengerExtendsActivity {
  2. /** The messenger object that sends the message to the Service */
  3. Messenger mservice =Null;
  4. /** Determine whether a service is bound */
  5. BooleanMbound;
  6. PrivateServiceconnection mconnection =NewServiceconnection (){
  7. Public VoidOnserviceconnected (componentname classname, ibinder Service ){
  8. // The activity has been bound to a service.
  9. // Create a messenger object using the parameter service. This object can send a message to the service and communicate with the service.
  10. Mservice =NewMessenger (service );
  11. Mbound =True;
  12. }
  13. Public VoidOnservicedisconnected (componentname classname ){
  14. Mservice =Null;
  15. Mbound =False;
  16. }
  17. };
  18. Public VoidSayhello (view v ){
  19. If(! Mbound)Return;
  20. // Send a message to the service
  21. Message MSG = message. Obtain (Null, Messengerservice. msg_say_hello,0,0);
  22. Try{
  23. Mservice. Send (MSG );
  24. }Catch(RemoteException e ){
  25. E. printstacktrace ();
  26. }
  27. }
  28. @ Override
  29. Protected VoidOncreate (bundle savedinstancestate ){
  30. Super. Oncreate (savedinstancestate );
  31. Setcontentview (R. layout. Main );
  32. }
  33. @ Override
  34. Protected VoidOnstart (){
  35. Super. Onstart ();
  36. // Bind the service
  37. Bindservice (NewIntent (This, Messengerservice.Class), Mconnection,
  38. Context. bind_auto_create );
  39. }
  40. @ Override
  41. Protected VoidOnstop (){
  42. Super. Onstop ();
  43. // Unbind
  44. If(Mbound ){
  45. Unbindservice (mconnection );
  46. Mbound =False;
  47. }
  48. }
  49. }

 Note: The code written above can only send messages from activity to service. If you want to send messages from service to activity, you only need to write the code in turn.

 

Use aidl

Aidl,Android Interface Definition Language.Creating an aidl service is more complex than creating a common service. The specific steps are as follows:

(1) Create an aidl file in the Java package directory of the eclipse Android project. The syntax of this file is similar to Java code, but it will be slightly different. For details, see the instance content. (2) If the content of the aidl file is correct, ADT will automatically generate a Java interface file (*. Java ). (3) create a service class ). (4) Implement the Java interface generated by the aidl file. (5) In androidmanifest. configure the aidl service in the XML file. Note that the value of the Android: Name attribute in the <action> tag is the ID of the service to be referenced by the client, that is, the parameter value of the intent class.

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.