Android 编写开启自启动的脚本服务

 前言

   因为公司有一款手机在升级之后用户找不到内部sdcard 中的数据,分析了主要原因是因为升级前后内部sdcard 的链接的路径改变了。之前sdcard的数据在/sdcard/emulated/ 目录下,升级时候放在了/sdcard/emulated/0/ 下面。一个解决方案就是在手机启动的时候开启一个脚本服务检测一下当前的目录是否是正确的,如果不对就进行目录得调整。主要的操作就是mv 操作,效率很高。


目录

1. 编写Shell脚本

2. fs_config.c 提交文件权限

3. 增加selinux te 文件,增加Shell脚本的一些权限

4. 添加新增文件上下文

5. 增加mk 文件实现编译拷贝

6. 在init.rc 中加入开机启动的Service


正文

1. 编写Shell 脚本

adjust_sdcard.sh

#!/system/bin/sh
i=1
num=0
while :
do
log -t ota-sdcard "try ..."$i
need_adjust=`ls /storage/emulated/ -l |grep "^d"|wc -l`
log -t ota-sdcard "need adjust ="$need_adjust
if [ "$need_adjust" == "2" ]
then
log -t ota-sdcard "adjust inner sdcard success ."
break
else
log -t ota-sdcard "try adjust inner adcard dir..."
for file in /storage/emulated/*
do
    if test -f $file
    then
        echo "move $file -> /storage/emulated/0/${file##*/}"
        log -t ota-sdcard "move $file -> /storage/emulated/0/${file##*/}"
        let num++
        mv $file /storage/emulated/0/${file##*/}
    fi
    if test -d $file && [ ${file##*/} != "0" ] && [ ${file##*/} != "obb" ]
    then
        echo "move $file -> /storage/emulated/0/${file##*/}"
        log -t ota-sdcard "move $file -> /storage/emulated/0/${file##*/}"
        let num++
        mv $file /storage/emulated/0/${file##*/}
    fi
done
log -t ota-sdcard "move num = $num"
fi
sleep 2
i=$(($i+1))
done

具体的功能就是判断一下目录结构对不对,如果不对就会调用mv 进行目录的调整。上面的脚本只是演示了主要的功能,用作调试用的。用兴趣可以看一下。


2. fs_config.c 提交文件权限

这个文件就是设置文件在系统中的权限

fs_path_config android_files 中增加
{ 00750, AID_ROOT, AID_ROOT, 0, "system/bin/adjust_sdcard.sh" },

3. 增加selinux te 文件,增加Shell脚本的一些权限
我们知道Android 4.4 之后引入了selinux的机制,所以我们编写的Shell的脚本的中很多命令代码都需要给予相应的selinux 权限。
#ota_sdcard.te
type ota_sdcard, domain;
type ota_sdcard_exec, exec_type, file_type;

init_daemon_domain(ota_sdcard)
allow ota_sdcard system_file:file execute_no_trans;
allow ota_sdcard shell_exec:file rx_file_perms;
allow ota_sdcard storage_file:dir search;
allow ota_sdcard fuse:dir {open read search getattr write remove_name rename add_name reparent};
allow ota_sdcard fuse:file {open read getattr write rename create};

4. 增加Shell 脚本文件的上下文
/system/bin/adjust_sdcard.sh u:object_r:ota_sdcard_exec:s0

5. 增加mk 文件实现编译拷贝
PRODUCT_COPY_FILES += \
device/qcom/msm8916/adjust_sdcard.sh:/system/bin/adjust_sdcard.sh

6. 在init.rc 中加入开机启动的Service
service ota-sdcard /system/bin/adjust_sdcard.sh
class main
oneshot
开机作为main 自启动。

上面的6个步骤是实现整个机制的核心步骤,细节并没有过多的讲述,后面增加每个步骤具体涉及到的知识点。





发布了35 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/ZHOUYONGXYZ/article/details/66969177