AIDL/IPC Android AIDL/IPC process communication mechanism-detailed explanation and usage case analysis (player)

Source: Internet
Author: User

AIDL/IPC Android AIDL/IPC process communication mechanism-detailed explanation and usage case analysis (player)

First, let's look at AIDL. What is AIDL? IPC? ------ Designing a Remote Interface Using AIDL

Generally, we use Binder and BroadCastReciver in the same process to allow the Service to communicate with the Activity, data interaction, and data sharing. But what about cross-process?

IPC: IPC interface, IPC interface local proxy ------ Implementing IPC Using AIDL

AIDL indicates Android Interface Define Language, which is the Android Interface Description Language.

Difference from J2ee: Java does not allow cross-Process Memory sharing. It only transmits objects. It adopts the RMI method and can also pass objects through serialization.

Android AIDL: The AIDL method can be used to transmit Bundle, which is a little more troublesome to implement.

Implementation process: Define the AIDL file on the server end. After the ADT plug-in Compiler compiles the file, the. java file is generated under the directory file of the R file at the same level. It is lightweight and uses the proxy class to transmit data between the client and implementation layers.

Deliver value

Syntax: You can declare interfaces and Methods. Parameters and return values are not of any type and do not need to declare import, String, charSequence, etc.

AIDL is not very troublesome to use. I personally feel very practical! So today I will talk about the features of AIDL. Many of my friends only talk about its theory in their blog, rather than writing some examples to explain it. I personally feel that you just want to talk about it.

In theory, the average person cannot understand it at all, and it is a very abstract thing, and you cannot understand it. It is also a white write if you write it!

Despite the feelings of new users, it is best to write some small examples so that everyone can join in and study and explore the best results! It's not a lot of text, and it doesn't look so boring. Do you say no?

Next, let's start to explain and learn about AIDL/IPC today ~, The concepts are almost the same. The next step is practice. The code example is for beginners to chew slowly.

Write from the server thread. structure diagram:


After EngineerJspRemoteService. aidl is written and saved, A. java file is automatically created in the gen file.


EngineerJspService. java

Package com. example. engineerjspserver;/*** AIDL/IPC * @ author Engineer-Jsp * @ date 2014.11.17 **/import java. io. fileDescriptor; 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 EngineerJspService extends Service {private static final String TAG = "EngineerJspServ Ice "; MediaPlayer player; @ Overridepublic IBinder onBind (Intent intent) {Log. d (TAG, "EngineerJspService is onBind... "+" \ n binding from the client has been completed... "); if (player = null) {player = MediaPlayer. create (this, R. raw. music); player = new MediaPlayer (); try {FileDescriptor file = getResources (). openRawResourceFd (R. raw. music ). getFileDescriptor (); player. setDataSource (file); player. setLooping (true);} catch (Exception e) {Lo G. d (TAG, e. toString ();} Log. d (TAG, "player is created... "+" \ n the server player has been instantiated and is ready... ");} return binder;} private IBinder binder = new EngineerJspRemoteService. stub () {@ Overridepublic void onStop () throws RemoteException {try {if (player. isPlaying () {Log. d (TAG, "the client process has paused the server process... "); player. stop () ;}} catch (Exception e) {Log. d (TAG, e. toString () ;}@ Overridepublic void onPause () throws RemoteException {t Ry {if (player. isPlaying () {return;} Log. d (TAG, "the client process has performed the start operation on the server process... "); player. prepare (); player. start ();} catch (Exception e) {Log. d (TAG, e. toString () ;}}; public boolean onUnbind (Intent intent) {if (player! = Null) {player. release ();} Log. d (TAG, "EngineerJspService is onUnBind... "+" \ n the client has been unbound and disconnected, and the service has stopped... "); return super. onUnbind (intent );};}
Configuration file:

 
     
                                
                                  
               
                   
              
                               
            
      
 

After completing the preceding operations, import the test file in the res. For example, if my test file is a music.pdf, it must be the same as the layout file.


After the server is completed, write the client thread and test the process communication.

Copy all the packages of aidl files on the server to src on the client, and delete all the packages except aidl files.


EngineerJspActivity. java

<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vc3Ryb25nPjxwcmUgY2xhc3M9 "brush: java;"> package com. example. engineerjspclient;/*** AIDL/IPC * @ author Engineer-Jsp * @ date 2014.11.17 **/import com. example. engineerjspserver. engineerJspRemoteService; import android. OS. bundle; import android. OS. IBinder; import android. util. log; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. toast; import android. app. activity; import android. content. componentName; import android. content. intent; import android. content. serviceConnection; public class EngineerJspActivity extends Activity {private static final String TAG = "EngineerJspActivity"; private static final String ACTION = "com. example. engineerjspserver. engineerJspService "; private EngineerJspRemoteService EJService; private boolean isBind = false; private Button onPause, onStart; private ServiceConnection connection = new ServiceConnection () {@ Overridepublic void onServiceDisconnected (ComponentName name) {isBind = false; EJService = null; Log. d (TAG, "onServiceDisconnected" + "----" + "package name:" + name. getPackageName () + "" + "Class name:" + name. getClassName () + "\ n when the client thread is disconnected, the service will be cleared... ") ;}@ Overridepublic void onServiceConnected (ComponentName, IBinder ibinder) {EJService = EngineerJspRemoteService. stub. asInterface (ibinder); isBind = true; Log. d (TAG, "onServiceConnected ----" + "package name:" + name. getPackageName () + "" + "Class name:" + name. getClassName () + "" + "ibinder object:" + ibinder. toString () + "\ n connecting the client thread to the server thread... ") ;};@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_engineer_jsp); Log. d (TAG, "the client thread Activity is successfully created, and the control is initialized and bound to the service... "); Bind (); intiView () ;}@ Override protected void onDestroy () {UnBind (); Log. d (TAG, "the client thread is destroyed, and the activity is unbound and stopped... "); super. onDestroy ();} public void Bind () {Log. d (TAG, "Activity has been created, and the Activity bound to the server thread is being executed... "); Intent intent = new Intent (ACTION); bindService (intent, connection, BIND_AUTO_CREATE);} public void UnBind () {if (isBind) {Log. d (TAG, "Activity is destroyed. Communication with the server thread will be unbound and stopped... "); unbindService (connection); EJService = null; isBind = false ;}} private void intiView () {onPause = (Button) findViewById (R. id. onPause); onStart = (Button) findViewById (R. id. onStop); onPause. setOnClickListener (listener); onStart. setOnClickListener (listener); Log. d (TAG, "the component initialization of the server thread is completed... ");} private OnClickListener listener = new OnClickListener () {@ Overridepublic void onClick (View view) {if (view. getId () = R. id. onPause) {try {EJService. onPause (); Log. d (TAG, "the client thread executes the playback operation on the server thread... "); Toast. makeText (EngineerJspActivity. this, "the client thread has played the server thread... ", Toast. LENGTH_SHORT ). show ();} catch (Exception e) {Log. d (TAG, e. toString () ;}} else {try {EJService. onStop (); Log. d (TAG, "the client thread has paused the server thread... "); Toast. makeText (EngineerJspActivity. this, "the client thread has paused the server thread... ", Toast. LENGTH_SHORT ). show ();} catch (Exception e) {Log. d (TAG, e. toString ());}}}};}
Activity_engineer_jsp.xml


      
       
   
  
Configuration file:

  
      
                           
                                   
                
               
  

Start the server process and client process (not in the same process, that is, not in the same APK Program), and view the process and stack in DDMS.


After the server process is enabled, it will wait for the client process to access and operate, similar to the c/s mode, Socket, after the client process is enabled, the server test data is as follows:


Client test data:


Service test:

The client process performs a playback operation on the server process:



The client process suspends the server process:




Two process project structure:


There is so much content in this small instance of AIDL, And the concept is similar. Please take a good look and digest it ~

For more highlights, please join us ~!

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.