You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何通过C++代码设置属性?

在Android C++中设置系统属性的API方式

所需头文件

直接引入Android原生的cutils头文件:

#include <cutils/properties.h>

可调用的核心API

使用property_set函数直接完成属性设置,函数原型:

int property_set(const char* key, const char* value);
  • 返回值:0代表设置成功,非0代表失败(常见原因包括权限不足、属性为只读类型等)
  • 若需要读取属性,可配套使用property_get:
    int property_get(const char* key, char* value, const char* default_value);
    

权限与注意事项

  • 属性类型限制:以ro.开头的是只读属性,无法通过该API修改;persist.、sys.等运行时属性支持修改,但需满足权限要求。
  • 权限要求:进程需拥有对应属性的修改权限,通常需要以root或system UID运行,或配置正确的SELinux规则,否则调用会返回失败。

代码示例

#include <cutils/properties.h>
#include <stdio.h>

int main() {
    // 设置可修改的自定义属性或系统属性
    int result = property_set("persist.my.test.prop", "hello_from_cpp");
    if (result == 0) {
        printf("属性设置成功\n");
    } else {
        printf("属性设置失败,错误码:%d\n", result);
    }
    return 0;
}

编译注意事项

编译时需要链接libcutils库:

  • 在Android.mk中添加:
    LOCAL_LDLIBS += -lcutils
    
  • 在CMakeLists.txt中添加:
    target_link_libraries(your_target_name cutils)
    

内容的提问来源于stack exchange,提问作者Nishant raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 07:34:50