Android系统中用C语言来编写服务程序并且开机自启动运行服务

以前我时常在想,怎么能在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权限问题说明

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零意@

您的打赏将是我继续创作的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值