Binder Learning Notes (i)

Source: Internet
Author: User

Read a lot of articles on the internet on binder, but I still want to record their own mental journey, some are following the footsteps of others to appreciate the steep scenery, some of their own alone into the code deep salvage of the harvest. I'm not sure I'm all over it, but I'm more worried about the way I'm going to be at a two-month time. The best way to verify and retain them is to write them down and read them back in a few months to see if they can read them clearly. If I can, it means that my two fears have ceased to exist, and if I return to foggy, I can continue to explore with new problems. The article many places will quote the Android source code, my source code version is 6.0.1_r11.

When static code goes through multiple states and relies on external data, it is often difficult to find a way to go in front of multiple fork junctions. I just stopped to pick up GDB, and the dynamic tune-up knew the right answer. I try to document the steps in detail so that it can be easily re-entered this way in the future.

I think reading code should also be "superficial understanding", do not Shidi, first on a level of analysis of the problem clearly, and then gradually into the next level, the level of breach. In fact, it is much like writing code, solving complex problems of two major weapons-layered, sub-modules. Of course, the ultimate goal is to reach the height of the moon, the bottom of the realm. The article will be released at 1.1 points, issued by the article may also be constantly back to revise, hope that the final can be polished out of a delicate sketch, and then no longer have to pursue binder.

Use of binder (Java code)

Binder is a way for the Android system to provide interprocess communication, which is often used when creating a service. The basic steps for creating a service are as follows:

Final Intent Intent = new Intent (this, bindmyservice.class);p rivate myserviceconnection conn = new myserviceconnection (); ... bindservice (intent, connection, service.bind_auto_create);  Create service
when service creation succeeds, the service will callback Serviceconnection's onservicecnnected function:

public void onserviceconnected (componentname name, IBinder service);

Even more amazing, the service and client can be two different processes, and even across processes, the client can still use binder from the service as a local object. Binder encapsulates a function call, assembles functions and parameters into a packet to the service, calls and executes the actual service interface by the service, and assembles the execution result into a packet back to the client.

Java layer code will go down into the native layer, through the layer of C + + code calls frameworks and the lower driver to complete the flow of messages. In order to touch the essence of binder as soon as possible, we now dive into the native layer, with C + + code to complete the service writing and client side of the call, and as a starting point into the binder implementation layer. As for the bridge from Java to native, it can be left to the essence of the problem to explore, it is only the small details on the last branch.

Use of binder (C + + code)
Test.h#ifndef __test_h__#define __test_h__#include <stdio.h> #include <binder/IInterface.h> #include <binder/Parcel.h> #include <binder/IBinder.h> #include <binder/Binder.h> #include <binder/ processstate.h> #include <binder/IPCThreadState.h> #include <binder/iservicemanager.h>using Namespace Android;namespace android{    class Itestservice:public iinterface    {public    :        Declare_meta_ INTERFACE (Testservice); Declare macro        virtual void Test () =0;    };    Enum    {        TEST = ibinder::first_call_transaction,    };    Class Bptestservice:public bpinterface<itestservice> {public    :        bptestservice (const sp<ibinder >& impl);        virtual void Test ();}    ;} #endif

 #include " Test.h "namespace android{implement_meta_interface (Testservice," Android. Testserver.itestservice ");} 
//TestClient.cpp #include "Test.h" namespace Android {bptestservice::bptestservice (const sp<ibinder>& impl): BPINTERFACE&L    T;itestservice> (impl) {}void bptestservice::test () {printf ("bptestservice::test () \ n");    Parcel data, reply;    Data.writeinterfacetoken (Itestservice::getinterfacedescriptor ());    Remote ()->transact (TEST, data, &reply); printf ("Reply:%d\n", Reply.readint32 ());}}    int main () {SP < Iservicemanager > SM = Defaultservicemanager ();    SP < IBinder > Binder = Sm->getservice (String16 ("Service.testservice"));    Sp<itestservice> cs = Interface_cast < Itestservice > (binder);    Cs->test (); return 0;} 
Testserver.cpp#include "Test.h" namespace Android {class Bntestservice:public bninterface<itestservice> { Public:virtual status_t ontransact (uint32_t code, const parcel& data, parcel* reply, uint32_t flags    = 0);    virtual void Test () {printf ("bntestservice::test () \ n"); }};status_t bntestservice::ontransact (uint_t code, const parcel& data, parcel* reply, uint32_t flags) {Swit        CH (code) {case TEST: {printf ("bntestservice::ontransact, code:test\n");        Check_interface (ITest, data, reply);        Test ();        Reply->writeint32 (100);    return no_error;    } break;    Default:break; } return no_error;}}    int main () {SP < processstate > proc (processstate::self ());    SP < iservicemanager > SM = Defaultservicemanager ();    Sm->addservice (String16 ("Service.testservice"), New Bntestservice ());    Processstate::self ()->startthreadpool (); Ipcthreadstate::self ()->jointhrEadpool (); return 0;}

#Android. Mklocal_path: = $ (call My-dir) #生成binder service side include $ (clear_vars) Local_shared_libraries: =     Libcutils     libutils     libbinder local_module    : = testserverlocal_src_files: =     TestServer.cpp     Itestservice.cpplocal_module_tags: = Optionalinclude $ (build_executable) #生成binder The test client side of the service include $ (clear_ VARS) Local_shared_libraries: =     libcutils     libutils     libbinder local_module    : = testclientlocal_src_ FILES: =     TestClient.cpp     itestservice.cpplocal_module_tags: = Optionalinclude $ (build_executable)

Create the folder Testservice under the Android source external directory and place the above five files under the folder. Execute the following command to complete the compilation:

$ mmm External/testservice

I changed the Target_build_type default value in the Android source build/envsetup.sh to debug, so that when the above MMM command is executed, the debug version is always generated. Once the compilation is complete, execute the following command

$ adb shell mkdir/data/local/tmp/testservice# copies the generated two executable programs to the emulator $ adb push out/debug/target/product/generic/obj/ executables/testserver_intermediates/linked/testserver/data/local/tmp/testservice$ ADB push out/debug/target/ product/generic/obj/executables/testclient_intermediates/linked/testclient/data/local/tmp/testservice# Add executable Permissions $ ADB shell chmod 755/data/local/tmp/testservice/*# start service side $ adb shell/data/local/tmp/testservice/ Testserverbntestservice::ontransact, Code:testbntestservice::test () # under another terminal client: $ adb shell/data/local/tmp/ Testservice/testclientbptestservice::test () Reply 100

OK, in preparation for this, you can then test the code for the entry into the internal implementation of the binder.


Binder Learning Notes (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.