Android-binder (i)

Source: Internet
Author: User

Android-binder (a) Learn from

Explore the art of Android development
Https://www.jianshu.com/p/bdef9e3178c9
72765136

Discussion on binder

Binder is an implementation class for the IBinder interface, and Inder is a bridge between the various managers and their service providers that connect the system, and binders are used primarily in service.

Layering of Android Systems

After we understand the layering of Android, we have a clearer understanding of the IPC, so let's take a look at the layering of the system

Let's look at the responsibilities of each layer in turn:

    • Linux Kernel (Linux kernel layer), this layer is mainly a variety of hardware drivers, Binder IPC driver is also in this layer
    • The HAL (Hardware abstraction layer), the encapsulation of the kernel layer, provides a callable interface to the system service layer in a jni manner.
    • Android system service (Android services layer), the core service of Android system, provides the interface for application layer to call
    • Binder IPC Proxys (Binder IPC agent layer) is a bridge between the application layer and the system service layer, enabling cross-process communication
    • Application Freamwork (Application framework layer), this is our SDK that provides the class library we use for our daily development

The Linux kernel layer is a good hardware abstraction layer, are implemented in C + +, the hardware abstraction layer will be compiled to so file, the JNI way to the system service layer call, the system service layer through Java implementation, the service in the layer with the mobile phone boot (not shutdown will always run), These services are responsible for the management of the activity, window management and so on. Because the system service layer is implemented through Java, they are definitely running with a separate Dalvik middle.

Because our programmers develop their own programs and system services are running in different virtual machines, communication between the only rely on IPC technology to complete, in order to facilitate the coder Call system service Interface Google provides a system services corresponding manager. The invocation relationship is as follows:

Starting from Aidl

Aidl (Android Interface definition Language) Androd Interface Definition language, through the AIDL can implement IPC, through the Aidl defined interface we can complete the client and service cross-process communication, Using Aidl, the system will automatically generate for us when compiling Binder .

Establish Aidl related files

Create the required entity class book to implement the Parcelable interface

 Package Top.littledavid.studyipc.beansimport android.os.Parcelimport android.os.parcelable/** * Created by IT on 7/30/2018. */class Book (Val bookid:int, Val bookname:string, Val author:string): parcelable {Constructor (parcel:parcel): th Is (Parcel.readint (), parcel.readstring (), parcel.readstring ()) {} Override fun WR Itetoparcel (Parcel:parcel, Flags:int) {parcel.writeint (bookId) parcel.writestring (bookname) Parcel . WriteString (author)} Override Fun Describecontents (): Int {return 0} override Fun ToString (): S Tring {return "book" (Bookid= $bookId, bookname= ' $bookName ', author= ' $author ') "} companion object Creator:pa Rcelable. creator<book> {override Createfromparcel (Parcel:parcel): Book {return book (parcel)} Override Fun NewArray (size:int): array<book?> {return arrayofnulls (size)}}} 

Set up the Aidl directory, enter a name, set up a directory to deconstruct, and then delete the file, we define our own files

Establish the Entity class mapping file Book.aidl to aidl under the same package as the book entity class, or it will be error, can not be compiled, the entity class of the package interface is top.littledavid.studyipc.beans->beans so aidl under the Book.aidl package will be the same.

//实体映射包名一定要和实体定义的包名相同package top.littledavid.studyipc.beans;//定义映射parcelable Book;

Defines IBookManager.aidl the method in which IPC operations are defined

// IBookManager.aidlpackage top.littledavid.studyipc;// Declare any non-default types here with import statementsimport top.littledavid.studyipc.beans.Book;interface IBookManager {    List<top.littledavid.studyipc.beans.Book> getBookList();    //这是如果不是使用的基础数据类型,一定要使用方向类型标识 : in ,out ,inout    void addBook(in Book book);}

The overall catalog is deconstructed as follows

A successful compilation will 项目路径\app\build\generated\source\aidl\debug\top\littledavid\studyipc generate one under (the package name may be different) IBookManager.java , which implements the IPC-related code.

Establish service
class BookService : Service() {    private lateinit var mBookList: MutableList<Book>    override fun onBind(intent: Intent?): IBinder {        mBookList = mutableListOf()        Log.e("TAG", "OnBind")        return mIBinder    }    //实现AIDL定义的接口    private val mIBinder = object : IBookManager.Stub() {        override fun getBookList(): List<Book> {            return [email protected]()        }        override fun addBook(book: Book) {            [email protected](book)        }    }}

Configuring services in the Minefast file

<service    android:name=".BookService"    android:enabled="true"    android:exported="true"    android:process=":remote" />
For IPC

IPC in activity

Class Mainactivity:appcompatactivity () {private var mibookmanager:ibookmanager? = null private val mconn = Objec t:serviceconnection {override fun onservicedisconnected (name:componentname?)  {Mibookmanager = null} override Fun onserviceconnected (name:componentname?, Service:ibinder?)    {//Convert IBinder to Aidl interface Mibookmanager = IBookManager.Stub.asInterface (Service)}} Override Fun OnCreate (Savedinstancestate:bundle?) {super.oncreate (savedinstancestate) Setcontentview (r.layout.activity_main)//opening service Val Service Bindintent = Android.content.Intent (this, Bookservice::class.java) This.bindservice (servicebindintent, Mconn, Conte Xt.        bind_auto_create)}//Add Book Info fun addbook (view:view) {val books = Book (1, "Android Development Art Quest", "Ningyugang teacher") This.mibookmanager!!. Addbook (book) Loadbookinfo ()} Private Fun Loadbookinfo () {val Booklist = mibookmanager!!. Booklist val stringBuilder = StringBuilder () Booklist.foreach {stringbuilder.append (it.tostring ( ) + "\ r \ n")} This.bookInfoTV.text = Stringbuilder.tostring ()} Override fun OnDestroy () {Supe R.ondestroy () This.unbindservice (Mconn)}}
Summarize

Stumbled on the completion of the AIDL IPC, thank you very much for the reference document Chinese bloggers selfless dedication. In the next chapter we look at the principle of binder.

Android-binder (i)

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.