Android Binder Mechanism -- (create binder Service)

Source: Internet
Author: User

Binder Mechanism Programming

The previous articles detail all aspects of the Binder Mechanism in Android. I believe you have a deep understanding of the binder mechanism. As the saying goes, we have learned how to use it. Next we will create our own binder service in the Android system to deepen our understanding of the binder mechanism.

(1) Add a new service name

There is a structure array allowed in the service_manager.c file. Add the new service name to the allowed struct array.

static struct {
    unsigned uid;
    const char *name;
} allowed[] = {
#ifdef LVMX
    { AID_MEDIA, "com.lifevibes.mx.ipc" },
#endif
    { AID_MEDIA, "media.audio_flinger" },
    { AID_MEDIA, "media.player" },
    { AID_MEDIA, "media.camera" },
    { AID_MEDIA, "media.audio_policy" },
    { AID_RADIO, "radio.phone" },
    { AID_RADIO, "radio.sms" },
    { AID_RADIO, "radio.phonesubinfo" },
    { AID_RADIO, "radio.simphonebook" },
/* TODO: remove after phone services are updated: */
    { AID_RADIO, "phone" },
    { AID_RADIO, "isms" },
    { AID_RADIO, "iphonesubinfo" },
{ AID_RADIO, "simphonebook" },
 
{AID_NEW, "newservice"}
};
 
(2) define the imyservice class

Define an interface class that inherits from the iinterface. It must start with an uppercase letter I. Taking imyservice as an example, the interface function must be a pure virtual function for production in the subclass, when defining an interface, declare_meta_interface macro is put into the interface class definition. The most important role of this macro is to convert the proxy object bpbinder into a service proxy object that is encapsulated cost-effectively (bpmyservice object here ), the code is roughly as follows:

Class ImyService:public IInterface
{
Public:
    DECLARE_META_INTERFACE(MyService);
        
    Virtual fun1() = 0;
    Virtual fun2() = 0;
}

 

(3) define a local implementation class bnmyservice

Define the interface implementation class bnmyservice in the imyservice. h header file. The interface must inherit from bninterface and indirectly inherit the imyservice interface class and bbinder class. The Code is as follows:

Class BnMyService:public BnInterface<IMyService>
{
Public:
    Virtual status_t onTransact(uint32_t code,
                                    const Parcel& data,
                                    Parcel* reply,
                                    uint32_t flags = 0);
}

 

(4) define the local proxy class bpmyservice

In the imyservice. cpp source file, the interface proxy class bpmyservice must be inherited from the bpinterface. Bpmyservice can provide interface functions defined by the imyservice interface.

class BpMyService: public BpInterface<IMyService>
{
public:
    BpMyService(const sp<IBinder>& impl)
        : BpInterface<IMyService>(impl)
    {
}
void fun1()
    {
        Parcel data, reply;
...... // Write data
Remote ()-> transact (enumeration, Data, & reply );
Return ...... // Return data
    }
……
}

 

(5) add macro definition

In the imyservice. cpp source file, add the macro definition implement_meta_interface ()

 
IMPLEMENT_META_INTERFACE(MyService, "XXX");
 

 

(6) define the ontransact () function of bnmyservice

The interface implementation class bnmyservice is implemented in the imyservice. cpp source file. The ontrasact () function executes different function calls based on the enumerated amount of the function code.

status_t BnMyService::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
Switch (CODE) {// code function code Enumeration
Case Function Code enumeration :{
            LOGV("NOTIFY_CALLBACK");
Check_interface (icameraclient, Data, reply); // check the descriptor string
...... // Parameter input, real implementation of interface functions
Reply-> ......); // Return data
            return NO_ERROR;
        } break;
……
default:
            return BBinder::onTransact(code, data, reply, flags);
}
}

 

(7) create a real local interface implementation class myservice class

Define the class myservice in the header file, inherit from bninterface, and define the function and the initialization function instantiate ():

Class MyService:public BnMyService
{
Public:
    Static void instantiate();
    
    Virtual func1();
    Virtual func2();
    ……
}
 
(8) define the myservice: instantiate () function
void MyService::instantiate() {
    defaultServiceManager()->addService(
            String16("newservice"), new MyService());
}
    
(9) register a service in the Service Process

When service process a is initialized, add the myservice: instantiate () function to register the service and call the jointhreadpool () function to wait for the call in a loop, listen for the request and process the request.

int main(int argc, char** argv)
{
    sp<ProcessState> proc(ProcessState::self());
    sp<IServiceManager> sm = defaultServiceManager();
    LOGI("ServiceManager: %p", sm.get());
    MyService::instantiate();
    ……
    ProcessState::self()->startThreadPool();
    IPCThreadState::self()->joinThreadPool();
}

 

(10) The client obtains the Service proxy object

Client process B wants to communicate with the server. First, it needs to obtain the proxy object of servicemanager, and then find the service. Because the service has been registered, a reference of this Service proxy object is returned, this proxy object contains a handle pointing to the searched service.

const sp<IMyService>& MyServiceSystem::get_MyService()
{
    Mutex::Autolock _l(mLock);
    if (gMyService.get() == 0) {
Sp <iservicemanager> Sm = defaultservicemanager (); // get the proxy of the Service Manager
// Object
        sp<IBinder> binder;
        do {
Binder = Sm-> getservice (string16 ("newservice"); // after finding the service,
// Return the proxy object of the service
            ……
        } while(true);
        ……
Gmyservice = interface_cast <imyservice> (binder); // convert it to the local server
// Bpmyservice)
        ……
    }
    ……
    return mMyService;
}

 

(11) client calls Server Functions

Client process B calls the imyservice interface function. The call is passed to the proxy object bpbinder containing the service object handle and written to the binder kernel driver. The binder driver knows the object to which the data is transmitted, so it passes the data to process.

Server process a reads data from the binder driver, processes remote calls, and sends reply data to the binder driver. The binder driver transmits reply to client process B. Process B reads data from the binder driver and obtains reply to complete process communication.

Status_t MyServiceSystem::func1()
{
    Const sp<IMyService>& af = MyServiceSystem::get_MyService();
    Af::Func1();
    ……
}

Here, we have finished introducing the Binder Mechanism in Android. Haha, I thought it would not be difficult to sum up the Binder Mechanism, but I still encountered many problems in the process of writing the summary. Haha, but fortunately, they all solved the problem one by one and finally finished writing. The summary process is equivalent to learning another Binder Mechanism, and there are new gains. It's really good!

 

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.