日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android 系统属性(SystemProperties)介绍

發布時間:2024/1/1 Android 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android 系统属性(SystemProperties)介绍 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我們在開發過程中有時需要使用系統屬性,例如獲取系統軟件版本,獲取設備名名稱等;有時也需要設置自己的屬性,為了全面的介紹系統屬性,本文將基于Android 10(Q)來介紹Android的屬性使用,圍繞以下幾點問題展開介紹:

  • prop的作用,如何調試和使用?
  • prop實現原理,代碼流程,prop存儲在哪里,何時init?
  • 如何添加自定義prop?

系統屬性簡單來說是用來存儲系統中某些鍵值對數據,具有全局性、存取靈活方便的特點。

一、終端prop命令

在終端設備中,可以通過以下命令進行prop調試。

1.1、查看prop

#查看系統所有props $getprop ... [persist.sys.timezone]: [Asia/Shanghai] //時區 [ro.system.build.type]: [userdebug] //系統編譯類型 [vendor.display.lcd_density]: [320] //屏幕密度 ...#獲取時區屬性persist.sys.timezone的值 $getprop persist.sys.timezone Asia/Shanghai#過濾屬性名或屬性值含有關鍵字"timezone"的屬性 $getprop | grep timezone [persist.sys.timezone]: [Asia/Shanghai]#獲取不存在的屬性時結果為空 $getprop hello

1.2、設置prop

$getprop my.prop.test //屬性my.prop.test為空 $setprop my.prop.test 123 //設置屬性my.prop.test為123 $getprop my.prop.test //獲取屬性my.prop.test為123 123

setprop 可以給屬性設置int、bool、string等基本類型

1.3、監聽prop

顯示屬性值發生變化的值

$watchprops [my.prop.test]: [123456]

二、get和set prop代碼流程

2.1、get和set prop代碼流程圖

涉及的代碼路徑匯總如下:

frameworks\base\core\java\android\os\SystemProperties.java frameworks\base\core\jni\android_os_SystemProperties.cpp system\core\base\properties.cpp system\core\init\main.cpp system\core\init\init.cpp system\core\init\property_service.cpp system\core\property_service\libpropertyinfoparser\property_info_parser.cpp bionic\libc\include\sys\_system_properties.h bionic\libc\include\sys\system_properties.h bionic\libc\bionic\system_property_set.cpp bionic\libc\bionic\system_property_api.cpp bionic\libc\system_properties\contexts_serialized.cpp bionic\libc\system_properties\system_properties.cpp bionic\libc\system_properties\prop_area.cpp

代碼流程整體時序圖如下:

系統屬性架構設計如下:

2.2、代碼流程介紹

frameworks\base\core\java\android\os\SystemProperties.java
Systemproperties類在android.os包下,因此使用時需要

import android.os.Systemproperties;

SystemProperties提供了setprop和多種返回數據類型的getprop,采用鍵值對(key-value)的數據格式進行操作,具體如下:

public class SystemProperties { ... public static final int PROP_VALUE_MAX = 91; @UnsupportedAppUsageprivate static native String native_get(String key);private static native String native_get(String key, String def);private static native int native_get_int(String key, int def);@UnsupportedAppUsageprivate static native long native_get_long(String key, long def);private static native boolean native_get_boolean(String key, boolean def);private static native void native_set(String key, String def);private static native void native_add_change_callback();private static native void native_report_sysprop_change(); ...//獲取屬性key的值,如果沒有該屬性則返回默認值defpublic static String get(@NonNull String key, @Nullable String def) {if (TRACK_KEY_ACCESS) onKeyAccess(key);return native_get(key, def);} ...//設置屬性key的值為val,其不可為空、不能是"ro."開頭的只讀屬性//長度不能超過PROP_VALUE_MAX(91)public static void set(@NonNull String key, @Nullable String val) {if (val != null && !val.startsWith("ro.") && val.length() > PROP_VALUE_MAX) {throw new IllegalArgumentException("value of system property '" + key+ "' is longer than " + PROP_VALUE_MAX + " characters: " + val);}if (TRACK_KEY_ACCESS) onKeyAccess(key);native_set(key, val);} }

通過JNI上述 native_set()和native_get()走到
frameworks\base\core\jni\android_os_SystemProperties.cpp

//獲取屬性的方法最終調用GetProperty() jstring SystemProperties_getSS(JNIEnv *env, jclass clazz, jstring keyJ,jstring defJ) {auto handler = [&](const std::string& key, jstring defJ) {std::string prop_val = android::base::GetProperty(key, "");...};return ConvertKeyAndForward(env, keyJ, defJ, handler); } jstring SystemProperties_getS(JNIEnv *env, jclass clazz, jstring keyJ) {return SystemProperties_getSS(env, clazz, keyJ, nullptr); }//設置屬性的接口最終調用SetProperty() void SystemProperties_set(JNIEnv *env, jobject clazz, jstring keyJ,jstring valJ) {auto handler = [&](const std::string& key, bool) {...return android::base::SetProperty(key, val);};... } ... //關聯SystemProperties.java與android_os_SystemProperties.cpp的方法 int register_android_os_SystemProperties(JNIEnv *env) {const JNINativeMethod method_table[] = {{ "native_get", "(Ljava/lang/String;)Ljava/lang/String;",(void*) SystemProperties_getS },{ "native_get","(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",(void*) SystemProperties_getSS },{ "native_set", "(Ljava/lang/String;Ljava/lang/String;)V",(void*) SystemProperties_set },...};return RegisterMethodsOrDie(env, "android/os/SystemProperties",method_table, NELEM(method_table)); }

跟著調用關系,接著進入:
system\core\base\properties.cpp

//調用__system_property_find()查找屬性值 std::string GetProperty(const std::string& key, const std::string& default_value) {...const prop_info* pi = __system_property_find(key.c_str());... } //調用__system_property_set()設置屬性值 bool SetProperty(const std::string& key, const std::string& value) {return (__system_property_set(key.c_str(), value.c_str()) == 0); }

觀察流程圖會發現這里會出現“岔路”,查詢和設置屬性的接口暫時走向不同文件接口

2.2.1、set prop流程

_system_properties.h頭文件定義PROP_SERVICE_NAME
bionic\libc\include\sys\_system_properties.h

#define PROP_SERVICE_NAME "property_service"

bionic\libc\bionic\system_property_set.cpp

static const char property_service_socket[] = "/dev/socket/" PROP_SERVICE_NAME; static const char* kServiceVersionPropertyName = "ro.property_service.version"; ... int __system_property_set(const char* key, const char* value) {if (g_propservice_protocol_version == 0) {detect_protocol_version();//獲取屬性服務協議版本}//舊協議版本限定prop name最大長度為PROP_NAME_MAX,prop val最大長度為PROP_VALUE_MAXif (g_propservice_protocol_version == kProtocolVersion1) {//在bionic\libc\include\sys\system_properties.h中定義//#define PROP_NAME_MAX 32//#define PROP_VALUE_MAX 92if (strlen(key) >= PROP_NAME_MAX) return -1;if (strlen(value) >= PROP_VALUE_MAX) return -1;...return send_prop_msg(&msg);//send_prop_msg()也通過Socket與property_service進行通信} else {//進入新版本協議,僅對prop val長度有要求,不超過92,且屬性不為只讀屬性// New protocol only allows long values for ro. properties only.if (strlen(value) >= PROP_VALUE_MAX && strncmp(key, "ro.", 3) != 0) return -1;...SocketWriter writer(&connection);//通過Socket與property_service進行通信...} ... static const char* kServiceVersionPropertyName = "ro.property_service.version"; static constexpr uint32_t kProtocolVersion1 = 1; static constexpr uint32_t kProtocolVersion2 = 2; // current static atomic_uint_least32_t g_propservice_protocol_version = 0; static void detect_protocol_version() {//從ro.property_service.version中獲取協議版本,可在平臺終端getprop ro.property_service.version//在后續2.2.5小節中可找到設置該屬性的位置if (__system_property_get(kServiceVersionPropertyName, value) == 0) {g_propservice_protocol_version = kProtocolVersion1;} else {uint32_t version = static_cast<uint32_t>(atoll(value));if (version >= kProtocolVersion2) {g_propservice_protocol_version = kProtocolVersion2;} else {g_propservice_protocol_version = kProtocolVersion1;}... }

2.2.2、屬性服務(property_service)

流程到了這里會發現,最終需要通過Socket與property_service來通信進行設置屬性值,那么問題來了:

  • property_service是誰創建的?
  • property_service是怎么啟動的?
  • property_service是如何setprop的?
    熟悉Android開機流程的同學會馬上聯想到init進程,property_service正是init進程來初始化和啟動的。

system\core\init\init.cpp

int SecondStageMain(int argc, char** argv) {...property_init();//屬性初始化...property_load_boot_defaults(load_debug_prop);//加載開機默認屬性配置StartPropertyService(&epoll);//啟動屬性服務... }

2.2.3、屬性初始化

system\core\init\property_service.cpp

void property_init() {mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH);CreateSerializedPropertyInfo();//創建屬性信息property_infoif (__system_property_area_init()) {//創建共享內存LOG(FATAL) << "Failed to initialize property area";}if (!property_info_area.LoadDefaultPath()) {LOG(FATAL) << "Failed to load serialized property info file";} } ... ... //讀取selinux模塊中的property相關文件,解析并加載到property_info中 void CreateSerializedPropertyInfo() {auto property_infos = std::vector<PropertyInfoEntry>();if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts",&property_infos)) {return;}// Don't check for failure here, so we always have a sane list of properties.// E.g. In case of recovery, the vendor partition will not have mounted and we// still need the system / platform properties to function.if (!LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts",&property_infos)) {// Fallback to nonplat_* if vendor_* doesn't exist.LoadPropertyInfoFromFile("/vendor/etc/selinux/nonplat_property_contexts",&property_infos);}if (access("/product/etc/selinux/product_property_contexts", R_OK) != -1) {LoadPropertyInfoFromFile("/product/etc/selinux/product_property_contexts",&property_infos);}if (access("/odm/etc/selinux/odm_property_contexts", R_OK) != -1) {LoadPropertyInfoFromFile("/odm/etc/selinux/odm_property_contexts", &property_infos);}} else {if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {return;}if (!LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos)) {// Fallback to nonplat_* if vendor_* doesn't exist.LoadPropertyInfoFromFile("/nonplat_property_contexts", &property_infos);}LoadPropertyInfoFromFile("/product_property_contexts", &property_infos);LoadPropertyInfoFromFile("/odm_property_contexts", &property_infos);}auto serialized_contexts = std::string();auto error = std::string();if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,&error)) {LOG(ERROR) << "Unable to serialize property contexts: " << error;return;}//將序列化屬性寫入/dev/__properties__/property_infoconstexpr static const char kPropertyInfosPath[] = "/dev/__properties__/property_info";if (!WriteStringToFile(serialized_contexts, kPropertyInfosPath, 0444, 0, 0, false)) {PLOG(ERROR) << "Unable to write serialized property infos to file";}selinux_android_restorecon(kPropertyInfosPath, 0); }

bionic\libc\bionic\system_property_api.cpp

int __system_property_area_init() {bool fsetxattr_failed = false;return system_properties.AreaInit(PROP_FILENAME, &fsetxattr_failed) && !fsetxattr_failed ? 0 : -1; }

初始化屬性內存共享區域
bionic\libc\system_properties\system_properties.cpp

bool SystemProperties::AreaInit(const char* filename, bool* fsetxattr_failed) {if (strlen(filename) >= PROP_FILENAME_MAX) {return false;}strcpy(property_filename_, filename);contexts_ = new (contexts_data_) ContextsSerialized();if (!contexts_->Initialize(true, property_filename_, fsetxattr_failed)) {return false;}initialized_ = true;return true; }

bionic\libc\system_properties\contexts_serialized.cpp

bool ContextsSerialized::Initialize(bool writable, const char* filename, bool* fsetxattr_failed) {filename_ = filename;if (!InitializeProperties()) {return false;}... } bool ContextsSerialized::InitializeProperties() {if (!property_info_area_file_.LoadDefaultPath()) {return false;}... }

system\core\property_service\libpropertyinfoparser\property_info_parser.cpp

bool PropertyInfoAreaFile::LoadDefaultPath() {return LoadPath("/dev/__properties__/property_info"); } bool PropertyInfoAreaFile::LoadPath(const char* filename) {int fd = open(filename, O_CLOEXEC | O_NOFOLLOW | O_RDONLY);...void* map_result = mmap(nullptr, mmap_size, PROT_READ, MAP_SHARED, fd, 0);... }

__system_property_area_init()經過一系列的方法調用,最終通過mmap()將/dev/__property __/property_info加載到共享內存。

2.2.4、加載開機默認屬性配置

接著init進程中property_load_boot_defaults(load_debug_prop)函數分析
system\core\init\property_service.cpp

void property_load_boot_defaults(bool load_debug_prop) {// TODO(b/117892318): merge prop.default and build.prop files into one// We read the properties and their values into a map, in order to always allow properties// loaded in the later property files to override the properties in loaded in the earlier// property files, regardless of if they are "ro." properties or not.std::map<std::string, std::string> properties;//加載屬性build.prop、default.prop至propertiesif (!load_properties_from_file("/system/etc/prop.default", nullptr, &properties)) {// Try recovery pathif (!load_properties_from_file("/prop.default", nullptr, &properties)) {// Try legacy pathload_properties_from_file("/default.prop", nullptr, &properties);}}load_properties_from_file("/system/build.prop", nullptr, &properties);load_properties_from_file("/vendor/default.prop", nullptr, &properties);load_properties_from_file("/vendor/build.prop", nullptr, &properties);if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_Q__) {load_properties_from_file("/odm/etc/build.prop", nullptr, &properties);} else {load_properties_from_file("/odm/default.prop", nullptr, &properties);load_properties_from_file("/odm/build.prop", nullptr, &properties);}load_properties_from_file("/product/build.prop", nullptr, &properties);load_properties_from_file("/product_services/build.prop", nullptr, &properties);load_properties_from_file("/factory/factory.prop", "ro.*", &properties);...//將properties中屬性通過PropertySet存入屬性屬性for (const auto& [name, value] : properties) {std::string error;if (PropertySet(name, value, &error) != PROP_SUCCESS) {LOG(ERROR) << "Could not set '" << name << "' to '" << value<< "' while loading .prop files" << error;}}property_initialize_ro_product_props();//初始化ro_product前綴的只讀屬性property_derive_build_props();//初始化編譯相關屬性update_sys_usb_config();//設置persist.sys.usb.config屬性,用于控制USB調試和文件傳輸功能 }

從上面代碼可以看出從多個屬性文件.prop中系統屬性加載至properties變量,再通過PropertySet()將properties添加到系統中,并初始化只讀、編譯、usb相關屬性值。
PropertySet()流程在2.2.1小節中有介紹,通過Socket與屬性服務進行通信,具體過程即將揭曉。

2.2.5、啟動屬性服務

2.2.2小節中提到init進程StartPropertyService(&epoll)啟動了屬性服務。
system\core\init\property_service.cpp

void StartPropertyService(Epoll* epoll) {selinux_callback cb;cb.func_audit = SelinuxAuditCallback;selinux_set_callback(SELINUX_CB_AUDIT, cb);//這里設置了2.2.1小節提到的屬性ro.property_service.versionproperty_set("ro.property_service.version", "2");property_set_fd = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,false, 0666, 0, 0, nullptr);if (property_set_fd == -1) {PLOG(FATAL) << "start_property_service socket creation failed";}listen(property_set_fd, 8);//設置Socket連接數為8//注冊epoll,監聽property_set_fd改變時調用handle_property_set_fdif (auto result = epoll->RegisterHandler(property_set_fd, handle_property_set_fd); !result) {PLOG(FATAL) << result.error();} } static void handle_property_set_fd() {...switch (cmd) {case PROP_MSG_SETPROP: {//設置屬性...uint32_t result =HandlePropertySet(prop_name, prop_value, socket.source_context(), cr, &error);...}case PROP_MSG_SETPROP2: {...uint32_t result = HandlePropertySet(name, value, socket.source_context(), cr, &error);...}... } uint32_t HandlePropertySet(const std::string& name, const std::string& value,const std::string& source_context, const ucred& cr, std::string* error) {if (auto ret = CheckPermissions(name, value, source_context, cr, error); ret != PROP_SUCCESS) {return ret;}if (StartsWith(name, "ctl.")) {//ctl屬性:ctl.start啟動服務,ctl.stop關閉服務HandleControlMessage(name.c_str() + 4, value, cr.pid);return PROP_SUCCESS;}// sys.powerctl is a special property that is used to make the device reboot. We want to log// any process that sets this property to be able to accurately blame the cause of a shutdown.if (name == "sys.powerctl") {//sys.powerctl屬性可控制設備重啟std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);std::string process_cmdline;std::string process_log_string;if (ReadFileToString(cmdline_path, &process_cmdline)) {// Since cmdline is null deliminated, .c_str() conveniently gives us just the process// path.process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());}LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid<< process_log_string;}if (name == "selinux.restorecon_recursive") {return PropertySetAsync(name, value, RestoreconRecursiveAsync, error);}return PropertySet(name, value, error);//設置屬性 } ... static uint32_t PropertySet(const std::string& name, const std::string& value, std::string* error) {size_t valuelen = value.size();if (!IsLegalPropertyName(name)) {//檢測屬性合法性*error = "Illegal property name";return PROP_ERROR_INVALID_NAME;}if (valuelen >= PROP_VALUE_MAX && !StartsWith(name, "ro.")) {*error = "Property value too long";return PROP_ERROR_INVALID_VALUE;}if (mbstowcs(nullptr, value.data(), 0) == static_cast<std::size_t>(-1)) {*error = "Value is not a UTF8 encoded string";return PROP_ERROR_INVALID_VALUE;}//檢測屬性是否已存在prop_info* pi = (prop_info*) __system_property_find(name.c_str());if (pi != nullptr) {// ro.* properties are actually "write-once".if (StartsWith(name, "ro.")) {*error = "Read-only property was already set";return PROP_ERROR_READ_ONLY_PROPERTY;}//屬性已存在,并且非ro只讀屬性,更新屬性值__system_property_update(pi, value.c_str(), valuelen);} else {//屬性不存在,添加屬性值int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);if (rc < 0) {*error = "__system_property_add failed";return PROP_ERROR_SET_FAILED;}}// Don't write properties to disk until after we have read all default// properties to prevent them from being overwritten by default values.if (persistent_properties_loaded && StartsWith(name, "persist.")) {WritePersistentProperty(name, value);//將persist屬性持久化到disk}property_changed(name, value);//特殊屬性值(如sys.powerctl)改變后系統需要立即處理。return PROP_SUCCESS; }

2.2.6、更新或添加屬性

bionic\libc\bionic\system_property_api.cpp

int __system_property_update(prop_info* pi, const char* value, unsigned int len) {return system_properties.Update(pi, value, len);//更新屬性值 } int __system_property_add(const char* name, unsigned int namelen, const char* value,unsigned int valuelen) {return system_properties.Add(name, namelen, value, valuelen);//添加屬性值 }

bionic\libc\system_properties\system_properties.cpp

int SystemProperties::Update(prop_info* pi, const char* value, unsigned int len) {...prop_area* pa = contexts_->GetSerialPropArea();uint32_t serial = atomic_load_explicit(&pi->serial, memory_order_relaxed);serial |= 1;atomic_store_explicit(&pi->serial, serial, memory_order_relaxed);atomic_thread_fence(memory_order_release);strlcpy(pi->value, value, len + 1);//屬性值更新...return 0; } int SystemProperties::Add(const char* name, unsigned int namelen, const char* value,unsigned int valuelen) {...prop_area* serial_pa = contexts_->GetSerialPropArea();prop_area* pa = contexts_->GetPropAreaForName(name);bool ret = pa->add(name, namelen, value, valuelen);//向共享內存添加新屬性...return 0; }

bionic\libc\system_properties\prop_area.cpp

bool prop_area::add(const char* name, unsigned int namelen, const char* value,unsigned int valuelen) {return find_property(root_node(), name, namelen, value, valuelen, true); } ... const prop_info* prop_area::find_property(prop_bt* const trie, const char* name, uint32_t namelen,const char* value, uint32_t valuelen,bool alloc_if_needed) {...prop_bt* root = nullptr;uint_least32_t children_offset = atomic_load_explicit(&current->children, memory_order_relaxed);if (children_offset != 0) {//找到屬性節點root = to_prop_bt(&current->children);} else if (alloc_if_needed) {//未找到時新建節點uint_least32_t new_offset;root = new_prop_bt(remaining_name, substr_size, &new_offset);if (root) {atomic_store_explicit(&current->children, new_offset, memory_order_release);}}...current = find_prop_bt(root, remaining_name, substr_size, alloc_if_needed);remaining_name = sep + 1;}uint_least32_t prop_offset = atomic_load_explicit(&current->prop, memory_order_relaxed);if (prop_offset != 0) {return to_prop_info(&current->prop);//返回已存在的prop_info} else if (alloc_if_needed) {uint_least32_t new_offset;//添加新屬性prop_info* new_info = new_prop_info(name, namelen, value, valuelen, &new_offset);...} } prop_info* prop_area::new_prop_info(const char* name, uint32_t namelen, const char* value,uint32_t valuelen, uint_least32_t* const off) {...prop_info* info;if (valuelen >= PROP_VALUE_MAX) {uint32_t long_value_offset = 0;char* long_location = reinterpret_cast<char*>(allocate_obj(valuelen + 1, &long_value_offset));if (!long_location) return nullptr;memcpy(long_location, value, valuelen);long_location[valuelen] = '\0';long_value_offset -= new_offset;info = new (p) prop_info(name, namelen, long_value_offset);} else {info = new (p) prop_info(name, namelen, value, valuelen);}*off = new_offset;return info; }

從上述code可分析出設置屬性流程中根據所設置的屬性值是否存在分別走update()和add()流程,而add 最后調用查找屬性方法,如果不存在則新建共享內存節點,將prop_info存入。自此,set prop流程結束。

2.2.7、get prop流程

承接2.2節system\core\base\properties.cpp中__system_property_find(key.c_str())
bionic\libc\bionic\system_property_api.cpp

const prop_info* __system_property_find(const char* name) {return system_properties.Find(name); }

bionic\libc\system_properties\system_properties.cpp

const prop_info* SystemProperties::Find(const char* name) {...prop_area* pa = contexts_->GetPropAreaForName(name);...return pa->find(name); }

bionic\libc\system_properties\prop_area.cpp

const prop_info* prop_area::find(const char* name) {return find_property(root_node(), name, strlen(name), nullptr, 0, false); }

find_property后續流程同2.2.6小節。

三、代碼中使用屬性

在上一章節中詳細介紹了獲取和設置屬性的代碼流程,但仍有部分問題仍待解決:

  • 2.2.4小節中build.prop、default.prop在哪里生成的,如何打包進系統
  • 如何添加自定義hello.prop
  • 如何添加系統級默認屬性
  • prop有哪些類型,不同前綴有什么區別
    上述疑問暫時先擱置一下,先來介紹在java、C++代碼中如何使用屬性

3.1、java代碼中使用prop

在java代碼中使用prop需滿足以下兩點:

  • import android.os.Systemproperties;
  • 具有system權限:
  • 在AndroidManifest.xml中,配置android:sharedUserId=“android.uid.system”
  • 在Android.mk中,配置LOCAL_CERTIFICATE :=platform

Systemproperties部分源碼如下:
frameworks\base\core\java\android\os\SystemProperties.java

... public class SystemProperties { ...//獲取屬性key的值,如果沒有該屬性則返回默認值defpublic static String get(@NonNull String key, @Nullable String def) {if (TRACK_KEY_ACCESS) onKeyAccess(key);return native_get(key, def);} ...//設置屬性key的值為valpublic static void set(@NonNull String key, @Nullable String val) {if (val != null && !val.startsWith("ro.") && val.length() > PROP_VALUE_MAX) {throw new IllegalArgumentException("value of system property '" + key+ "' is longer than " + PROP_VALUE_MAX + " characters: " + val);}if (TRACK_KEY_ACCESS) onKeyAccess(key);native_set(key, val);} .... }

get和set pro以ActivityManagerService.java代碼為例:
frameworks\base\services\core\java\com\android\server\am\ActivityManagerService.java

final void finishBooting() {...//設置開機完成標志屬性sys.boot_completedSystemProperties.set("sys.boot_completed", "1"); } ... private static void maybePruneOldTraces(File tracesDir) {...//獲取tombstoned.max_anr_count屬性值final int max = SystemProperties.getInt("tombstoned.max_anr_count", 64); }

獲取屬性值可以根據值的類型使用合適返回值類型的方法如getInt()、getBoolean()、getLong(),SystemProperties.get()獲取的值為String。

3.2、C++代碼中使用prop

這里以MPEG4Writer.cpp為例
frameworks\av\media\libstagefright\MPEG4Writer.cpp

#include <cutils/properties.h>... void MPEG4Writer::addDeviceMeta() {...if (property_get("ro.build.version.release", val, NULL)...if (property_get("ro.product.model", val, NULL)... }

在C++代碼中使用prop需要:

  • include <cutils/properties.h>
  • Android.mk或Android.bp或Makefile中需要鏈接libcutils庫

properties.h源碼在:
system/core/libcutils/include/cutils/properties.h

int property_get(const char* key, char* value, const char* default_value); int property_set(const char *key, const char *value); int property_list(void (*propfn)(const char *key, const char *value, void *cookie), void *cookie);

3.3、特殊屬性

從2.2.5小節中可以看到有些屬性比較特殊,特總結如下:

3.3.1、 ro只讀屬性

ro即read only這類屬性通常是系統默認屬性,在系統編譯或初始化時設置的。

$ getprop ro.vendor.build.version.release 10 $ setprop ro.vendor.build.version.release 9 setprop: failed to set property 'ro.vendor.build.version.release' to '9'

3.3.2、persist持久屬性

設置persist開頭的屬性,斷電后仍能保存,值寫入data/property/persistent_properties。

$ getprop persist.hello.test //屬性為空 $ setprop persist.hello.test abc //設置屬性persist.hello.test值為abc $ getprop persist.hello.test abc //屬性get正常 abc $reboot //重啟設備 $ getprop persist.hello.test //屬性為abc abc

3.3.3、ctl 控制屬性

setprop ctl.start xxx //啟動某服務 setprop ctl.stop xxx //關閉某服務 setprop ctl.restart xxx //重啟某服務

3.3.4、sys.powerctl屬性

sys.powerctl屬性可控制設備重啟關機

setprop sys.powerctl shutdown //設備關機 setprop sys.powerctl reboot //設備重啟

3.3.5、普通屬性

設置其他格式開頭的屬性,斷電后不能保存

$ getprop hello.test //屬性為空 $ setprop hello.test 123//設置屬性persist.hello.test值為abc $ getprop hello.test 123//屬性get正常 123 $reboot //重啟設備 $ getprop hello.test //屬性為空

3.4、添加系統默認屬性

從前面的介紹中我們知道系統開機時會load *.prop屬性配置文件中的屬性,因此開機后就有了默認屬性。這里我們可以在device/xxx/xxx/system.prop 中添加
device/google/marlin/system.prop

# 添加自己的系統默認屬性 persist.hello.world=hello

注意:這里添加的屬性前綴必須是在system/sepolicy/private/property_contexts中被定義過的,否則無效;定制化前綴屬性在后面定制prop屬性配置中會介紹。
make android后在out/target/product/xxx/system/build.prop 或out/target/product/xxx/vendor/build.prop可找到添加的屬性persist.hello.world,則說明基本添加成功,燒錄img驗證即可。

四、prop打包

我們已經知道如何添加系統默認屬性,但項目中有許多*.prop配置文件,

  • 這些文件是如何最終打包至out/tartget/product/…/build.prop的呢?
  • 為了便于客制化屬性管控,如何添加自己的prop配置文件呢?

本章將圍繞上面兩個問題進行介紹

4.1、prop打包流程

build.prop是由代碼編譯時,build/core/Makefile完成的

//指定編譯信息及設備基本信息腳本 BUILDINFO_SH := build/make/tools/buildinfo.sh BUILDINFO_COMMON_SH := build/make/tools/buildinfo_common.sh//指定build.prop生成路徑 INSTALLED_BUILD_PROP_TARGET := $(TARGET_OUT)/build.prop INSTALLED_PRODUCT_BUILD_PROP_TARGET := $(TARGET_OUT_PRODUCT)/build.prop INSTALLED_VENDOR_BUILD_PROP_TARGET := $(TARGET_OUT_VENDOR)/build.prop ... //生成build.prop $(intermediate_system_build_prop): $(BUILDINFO_SH) $(BUILDINFO_COMMON_SH) $(INTERNAL_BUILD_ID_MAKEFILE) $(BUILD_SYSTEM)/version_defaults.mk $(system_prop_file) $(INSTALLED_ANDROID_INFO_TXT_TARGET) $(API_FINGERPRINT)@echo Target buildinfo: $@@mkdir -p $(dir $@)$(hide) echo > $@ ifneq ($(PRODUCT_OEM_PROPERTIES),)$(hide) echo "#" >> $@; \echo "# PRODUCT_OEM_PROPERTIES" >> $@; \echo "#" >> $@;$(hide) $(foreach prop,$(PRODUCT_OEM_PROPERTIES), \echo "import /oem/oem.prop $(prop)" >> $@;) endif$(hide) PRODUCT_BRAND="$(PRODUCT_SYSTEM_BRAND)" \...TARGET_CPU_ABI2="$(TARGET_CPU_ABI2)" \bash $(BUILDINFO_SH) >> $@//將許多屬性追加至out/.../build.prop

build/make/tools/buildinfo.sh中配置了系統編譯常見信息,具體如下

... echo "ro.build.version.incremental=$BUILD_NUMBER"//軟件增量版本 echo "ro.build.version.sdk=$PLATFORM_SDK_VERSION"//軟件使用的sdk版本 echo "ro.build.version.release=$PLATFORM_VERSION"//系統版本號 echo "ro.build.date=`$DATE`"//軟件編譯日期 ...

經過Makefile,將系統中各種prop配置文件合并生成在out指定路徑下。
也是在Makefile中將各路徑下build.prop隨系統分區一同打包進img,out\target\product\xxx\system\build.prop打包進system.img
out\target\product\xxx\vendor\build.prop打包進vendor.img

五、添加定制hello.prop

涉及的代碼路徑匯總如下:

device/qcom/qssi/hello.prop device/qcom/qssi/qssi.mk device/qcom/sepolicy/generic/private/property_contexts system/core/rootdir/init.rc system/core/init/property_service.cpp

為了方便統一管理定制化屬性,有時會將定制化屬性都寫在定制的.prop文件中,下面以添加hello.prop為例說明添加過程。

5.1、device下添加hello.prop

device/qcom/qssi/hello.prop

# # system.prop for qssi # ro.hello.year=2022 //添加ro屬性 persist.hello.month=07 //添加persist屬性 hello.day=25 //添加hello屬性ro.product.model=HelloWorld //定制系統已有ro.product.model屬性

5.2 配置預置路徑

修改device下的device.mk來指定hello.prop的預置路徑
device/qcom/qssi/qssi.mk

#將hello.prop預置到system/hello.prop PRODUCT_COPY_FILES += \device/qcom/qssi/hello.prop:system/hello.prop

5.3、SELinux權限配置

hello.開頭的屬性是新添加的配置,需要在配置對應的SELinux規則,否則無效,配置方法如下:
device/qcom/sepolicy/generic/private/property_contexts

hello. u:object_r:system_prop:s0

5.4、配置hello.prop權限

此步驟可省略,若未配置讀寫權限,默認system/prop為644
這里配置與system/build.prop相同的600權限
system/core/rootdir/init.rc

on fschmod 0600 /system/hello.prop

5.5、load hello.prop

5.2、小節中僅僅將hello.prop預置到system/hello.prop還不夠,系統啟動時需要load hello.prop才能使其生效
system/core/init/property_service.cpp

load_properties_from_file("/system/build.prop", nullptr, &properties);load_properties_from_file("/vendor/default.prop", nullptr, &properties);load_properties_from_file("/vendor/build.prop", nullptr, &properties);if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_Q__) {load_properties_from_file("/odm/etc/build.prop", nullptr, &properties);} else {load_properties_from_file("/odm/default.prop", nullptr, &properties);load_properties_from_file("/odm/build.prop", nullptr, &properties);}load_properties_from_file("/product/build.prop", nullptr, &properties);load_properties_from_file("/product_services/build.prop", nullptr, &properties);load_properties_from_file("/factory/factory.prop", "ro.*", &properties);//load 預置的hello.prop ,最后load保證其配置屬性優先級更高load_properties_from_file("/system/hello.prop", nullptr, &properties);

5.6、驗證hello.prop

Android全編譯后正常情況可找到生成的
out/target/product/qssi/system/hello.prop

檢查其內容應與device/qcom/qssi/hello.prop內容保持一致。
將打包好的img燒錄到設備中進行確認

//hello.prop預置成功 $ ls -al system/ -rw-r--r-- 1 root root 117 2009-01-01 08:00 hello.prop//新增屬性設置成功 $ getprop | grep hello [hello.day]: [25] [persist.hello.month]: [07] [ro.hello.year]: [2022]//ro.product.model覆蓋了默認值 $ getprop ro.product.model HelloWorld

總結

以上是生活随笔為你收集整理的Android 系统属性(SystemProperties)介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 亚洲国产免费看 | 中文字幕欧美专区 | 亚洲91视频 | 黄色av中文字幕 | 成人欧美一区二区三区黑人 | 黄色av网站免费观看 | 涩涩涩涩涩涩涩涩涩涩 | 亚洲图片综合区 | 嫩草影院懂你的影院 | 国产女人18毛片水真多 | 日韩久久精品一区二区 | 亚洲免费观看高清在线观看 | 色婷婷18 | 日本男人天堂网 | 激情午夜视频 | 色播五月激情五月 | 国产初高中真实精品视频 | 操操操操网 | 免费毛片在线播放 | 在线不卡毛片 | 国产精品黑人一区二区三区 | 红色假期黑色婚礼2 | 波多野结衣中文字幕久久 | 亚洲免费大全 | 欧美成人精品欧美一级 | 好看的毛片 | 日韩专区欧美专区 | 理论片在线观看视频 | 91精品一区二区三 | av老司机在线播放 | 欧美69久成人做爰视频 | 奇米影视四色777 | 黄色网页在线 | 色综合精品 | 精品国产一区一区二区三亚瑟 | 亲子乱一区二区三区 | 国产精品亚洲天堂 | www.超碰在线 | 蜜桃av一区二区 | 波多在线视频 | 午夜国产福利在线 | 丝袜美腿中文字幕 | v片在线看 | 天天色影院 | 欧美激情五月 | 久久精品色欲国产AV一区二区 | 午夜资源 | 三上悠亚久久精品 | 麻豆av片| 亚洲精品1区| 啪啪啪一区二区 | 国产在线视频自拍 | 国产一卡二 | 一区二区三区四区欧美 | 麻豆乱码国产一区二区三区 | 成人蜜桃av | 综合亚洲视频 | 日本草草视频 | 国产女人18水真多18精品一级做 | 欧美性猛交xxxx乱大交退制版 | 日韩av线观看 | 2020av视频| 中文在线观看免费视频 | 桃谷绘里香在线观看 | 一个人看的www片免费高清中文 | 日韩在线免费 | 人人做人人爱人人爽 | 91精品国产一区二区三竹菊影视 | 丰满大乳少妇在线观看网站 | 欧美三级黄 | 无套内谢的新婚少妇国语播放 | 亚洲制服一区二区 | 国产资源一区 | 一级做a在线观看 | 中文字幕3区 | 久久人久久 | 可以免费在线观看的av | 少妇专区 | 免费爱爱网址 | 欧美三级免费看 | 男人干女人视频 | 三级欧美日韩 | 黄色一毛片 | 国产视频网站在线观看 | 国产一区二区精品在线观看 | 奇米在线777 | 亚洲一区日本 | 色妞色视频一区二区三区四区 | 日韩成人av免费在线观看 | 亚洲av无码一区二区三区dv | 欧美午夜精品一区二区蜜桃 | 亚洲成色网 | 999这里有精品| 中文字幕一区二区三区门四区五区 | 亚洲国产精品麻豆 | 亚洲欧美日韩在线一区二区 | 亲子乱一区二区三区 | 国产日韩欧美亚洲 | 国产无码日韩精品 |