以前我时常在想,怎么能在Android系统中用C语言来编写应用程序呢?Android系统上的应用程序不都是Java应用程序吗?其实是可以的,读者不妨用adb shell命令连上Android模拟器,在/system/bin目录下可以看到很多C可执行程序,如cat命令。今天,我们就来学习一下怎么在Android系统中添加用C语言编写的可执行程序。
还是以hello world来讲吧。毕竟大家对这个比较熟。
进入到Android源代码工程的external目录,创建hello目录,
caizd@blsx:~/mt6580_androidL$ cd external/
caizd@blsx:~/mt6580_androidL/external$ mkdir hello
在hello目录中新建hello.c文件,并且添加代码如下:
#include <stdio.h>
int main(int argc, char** argv)
{
printf("Hello World!\n");
return 0;
}
这个程序的作用是打印出Hello World!
然后在hello目录中新建Android.mk文件,添加代码:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE := hello
LOCAL_SRC_FILES := $(call all-subdir-c-files)
include $(BUILD_EXECUTABLE)
注意,BUILD_EXECUTABLE表示我们要编译的是可执行程序
使用mmm命令进行编译:
caizd@blsx:~/mt6580_androidL/external$ mmm ./external/hello
编译成功后,就可以在out/target/product/inwatch_portal/system/bin/目录下,看到可执行文件hello了。
然后通过adb工具把hello push到机器的system/bin/,给755权限即可。然后执行adb 进入机器执行./hello,即可看到打印Hello World!,说明操作成功。具体操作命令如下:
C:\Users\asus>adb root
adbd is already running as root
C:\Users\asus>adb remount
remount succeeded
C:\Users\asus>adb push Y:\mt6580_androidL\out\target\product\inwatch_portal\system\bin\hello system/bin
55 KB/s (5412 bytes in 0.094s)
C:\Users\asus>adb shell
root@inwatch_portal:/ # cd system/bin
cd system/bin
root@inwatch_portal:/system/bin # chmod 755 hello
chmod 755 hello
root@inwatch_portal:/system/bin # ./hello
./hello
Hello World!
root@inwatch_portal:/system/bin #
如果需要这个执行文件在开机之后在后台自动运行,则需要添加以下语句到init.rc的文件或者xxxx.sh中(一定要是能运行的rc文件或者sh文件)。Unix/Linux下一般比如想让某个程序在后台运行,很多都是使用 & 在程序结尾来让程序自动运行。比如我们要运行hello在后台:
1、xxxx.sh中添加:
/system/bin/hello &
2、init.rc添加,不需要&:
Below Android 4.0(安卓4.0之前)
service hello /system/bin/hello
user root
group root
oneshot
Above Android 4.0(安卓4.0之后)
service hello /system/bin/hello
class main
user root
group root
oneshot
seclabel u:r:hello:s0 #这句是为加selinux权限添加的,android5.1以后不加则无法启动该服务
当然了,加完了上面这些之后,还需要处理一下Selinux的一些权限的问题,否则会出现如下报错:
[ 4.099220] init: Starting service 'hello'...
[ 4.101726] init: cannot setexeccon('u:r:ehello:s0'): Invalid argument
[ 4.147480] init: Service 'hello' (pid 242) exited with status 12
具体的处理可以参考:添加开机启动服务程序关于Selinux权限问题说明