2025年3月24日 星期一 甲辰(龙)年 月廿三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > 安卓(android)开发

Android开机自动执行脚本

时间:04-14来源:作者:点击数:48

0.前言

由于作者本人初次接触Android,所以本文所述内容只是操作方法,没有深究原理。各位可自行深入学习研究。

1.需求描述

需要在Android开机启动之后,自动执行一个脚本,假设这个脚本是test.sh。脚本中只执行1条打印:

  • #!/bin/bash
  • echo "auto start test.sh!"

2.需求分析

根据需求描述,可以推导有两件事情要做:

  1. 首先将test.sh脚本文件预置到Android中的某个路径下,假设放在system/app;
  2. 编译后,下载到开发板,上电自动执行test.sh脚本。

3.操作步骤

  1. 添加rc文件,如下:注意rc文件最后一定要有空行,否则编译报错!
  • service test /system/app/test.sh
  • class main
  • user root
  • group root
  • on property:sys.boot_completed=1
  • start test
  1. 预置文件,参考Android系统预置文件。将test.sh脚本拷贝到相应的路径上。比如,我将其放在/system/app下;将rc文件预置到out/target/product/xxx/system/etc/init下(xxx是你的项目名称)。Android.mk如下:
  • LOCAL_PATH := $(call my-dir)
  • include $(CLEAR_VARS)
  • $(shell cp -af $(LOCAL_PATH)/test.sh $(TARGET_OUT)/app)
  • $(shell cp -af $(LOCAL_PATH)/test.rc $(TARGET_OUT)/etc/init)
  1. 还可能需要给test.sh赋予执行权限。我的是在fs_config.cpp中修改权限的。
  • static const struct fs_path_config android_files[] = {
  • //省略其他不相关权限配置
  • { 00755, AID_ROOT, AID_SHELL, 0, "system/app/*"},//给/system/app下的文件赋予755权限
  • //省略其他不相关权限配置
  • };
  1. 整体编译后,烧写到开发板,可自动执行。

4.待完善

按照第3节步骤操作完成后,通过adb shell指令,查看日志,如下:

  • test:/ $ cd system/app
  • test:/system/app $ ls -l
  • -rwxr-xr-x 1 root shell 26 2022-02-09 20:13 test.sh
  • test:/system/app $ logcat |grep test.sh
  • 01-01 08:00:16.657 0 0 E init : Could not start service 'test' as part of class 'main': File /system/app/test.sh(labeled "u:object_r:system_file:s0") has incorrect label or no domain transition from u:r:init:s0 to another SELinux domain defined. Have you configured your service correctly? https://source.android.com/security/selinux/device-policy#label_new_services_and_address_denials
  • 02-10 11:10:22.710 0 0 I init : Command 'start test' action=sys.boot_completed=1 (/system/etc/init/test.rc:7) took 0ms and failed: Could not start service: File /system/app/test.sh(labeled "u:object_r:system_file:s0") has incorrect label or no domain transition from u:r:init:s0 to another SELinux domain defined. Have you configured your service correctly? https://source.android.com/security/selinux/device-policy#label_new_services_and_address_denials

可以看到确实自动执行了test.rc文件,只不过在执行/system/app/test.sh时出错了,原因是SELinux的问题。这部分我还没有深入研究,待后期完善。只要解决了SELinux的权限问题,就可以正常启动test.sh了。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门