Kan-Ru Chen's Weblog

Android Service with dynamic arguments

Recently when I was preparing some Android training material I found this little trick.

Android "init" can do a lot of things, including "on property change" trigger; one can image some applications use this to implement an ad-hoc IPC. One example is the system/libnetutil that monitors the "init.svc.dhcpcd" property to detect whether dhcpcd is running or not.

Android framework can execute some predefined command (service) via the "ctl.start" property, the most interesting part is you can supply dynamic arguments to the command just like you were calling a command from shell.

The format is

    setprop ctl.start service:arg1 arg2 arg3..

It must be a oneshot service, for example you can define a dhcpcd service like:

    service dhcpcd /system/bin/dhcpcd -B
        group dhcp wifi system
        disabled
        oneshot

And set the target interface dynamically:

    setprop ctl.start dhcpcd:eth0

"init" will then execute "dhcpcd -B eth0" with appropriate permissions.