在android中有时候我们需要通过应用查看一个文件是否有被其他文件操作,在linux命令行下可以通过fuser命令查看,如果上层的android应用直接调用该程序则由于受权限影响无法查看(fuser会通过/proc文件系统来搜集相关的操作文件的信息),即fuser只有在root 权限下才能充分发挥查看占用的问题。要达到这个目的,可以将fuer变为一个运行于root权限下的按需调用的服务,通过该服务间接实现查看文件的目的。服务和应用之间的通讯可以通过property来进行。具体如下:
修改init.rc文件,加入fuser service。
service fuser /system/bin/fuser.sh
user root
oneshot
disabled
增加fuser.sh运行脚本如下:
#!/system/bin/busybox sh
#app will set boot.CHK_FILE to the file(absolute path) he wants to check,then trigger this service
#the result will be incuded in the proprity ,0 means occupied, 1 means file not exist or some error occuor.
/system/bin/setprop "boot.LOOK_PROG_RES" ""
/system/bin/setprop "boot.LOOK_PROG_STAT" "beginning"
PRG=`/system/bin/getprop "boot.CHK_FILE"`
/system/bin/busybox fuser $PRG
CHK_RESULT=$?
echo check prg=$PRG,result=$CHK_RESULT
/system/bin/setprop "boot.LOOK_PROG_RES" "$CHK_RESULT"
/system/bin/setprop "boot.LOOK_PROG_STAT" "end"
在应用代码中嵌入如下代码:
SystemProperties.set("boot.CHK_FILE", "/sdcard/music/zh.mp3");
SystemProperties.set("boot.LOOK_PROG_STAT","");
SystemService.start("fuser");
try{Thread.sleep(1000);}catch(Exception e){}
while(SystemProperties.get("boot.LOOK_PROG_STAT").compareTo("end")!=0)
{
Log.v("boot.LOOK_PROG_STAT="+SystemProperties.get("boot.LOOK_PROG_STAT"));
try{Thread.sleep(100);}catch(Exception e){}
}
Log.v("====get check result:"+SystemProperties.get("boot.LOOK_PROG_RES"));
即可实现是否检查/sdcard/music/zh.mp3是否有被其他程序操作。
注意应用代码的manifest中需要加入system权限:
android:sharedUserId="android.uid.system"
此外还需调整修改property_service.c,加入新的boot对system的权限。