前言
客户需求,需要判断设备是否执在root状态。可以理解为是否执行了adb root 设置root状态,已经adb unroot设置unroot状态。
代码分析
分析adb deamon发现:在执行adb root 、adb unroot指令时,系统会更新service.adb.root 变量。
bash
void restart_root_service(unique_fd fd) {
if (getuid() == 0) {
WriteFdExactly(fd.get(), "adbd is already running as root\n");
return;
}
if (!__android_log_is_debuggable()) {
WriteFdExactly(fd.get(), "adbd cannot run as root in production builds\n");
return;
}
LOG(INFO) << "adbd restarting as root";
android::base::SetProperty("service.adb.root", "1");
WriteFdExactly(fd.get(), "restarting adbd as root\n");
}
void restart_unroot_service(unique_fd fd) {
if (getuid() != 0) {
WriteFdExactly(fd.get(), "adbd not running as root\n");
return;
}
LOG(INFO) << "adbd restarting as nonroot";
android::base::SetProperty("service.adb.root", "0");
WriteFdExactly(fd.get(), "restarting adbd as non root\n");
}
实现
系统应用可以通过SystemProperties get "service.adb.root" value来判断是否root。
bash
public static final String ADB_ROOT_PROP = "service.adb.root";
public static boolean deviceIsRooted(){
return SystemProperties.getInt(ADB_ROOT_PROP,0) == 1 ? true:false;
}