Lab – Adding Native Service

1.create a stand alone service

  • Add a new directory in ~/aosp/external – loggerTest
  • Create a makefile – (copy from netcat and make changes)
  • Add the following source:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main() {
    int fd=open("data1",O_RDWR|O_CREAT,0660);
    char buffer[100];
    struct sockaddr_in addr = {0};
    size_t addrlen, n;
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(2000);
    addr.sin_addr.s_addr = INADDR_ANY;
    bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
    addrlen = sizeof(addr);
        n = recvfrom(sockfd, (void*)buffer, 100, 0,
		(struct sockaddr*)&addr, (unsigned int *) &addrlen);
        buffer[n] = '\n';
    return 0;
  1. compile the rom, run the emulator and start the service using adb:
  • cd ~/aosp
  • source build/
  • lunch 1
  • make
  • emulator &
  • adb shell
  • cd data
  • loggerTest &
  1. create android application to use it
  • create a simple activity with one button
  • implement click event: create and start a thread to run the following code:
    void sendonemsg()
		DatagramSocket s;
		try {
			s = new DatagramSocket();
			InetAddress local = InetAddress.getByName("");
			String str="hello service";
			int msg_length = str.length();
			DatagramPacket p = new DatagramPacket(str.getBytes(), msg_length, local, 2000);
		} catch (Exception e) {
			// TODO Auto-generated catch block
  • add internet permissions to the project
  • run the application on the custom device

4. Edit init.rc file to make the service run on reset and test your work

5. Edit init.rc file to make the service start on system property loggertest.enable=1 and stop on system property loggertest.enable=0

6. Write a simple utility to set the above system property using libcutils property_set function. Use /system/core/reboot as an example