Android 使用SystemProperties读写属性值

在Android系统中,经常使用SystemProperties去读写全局的属性值,通常这个属性值是存放在文件中的,在Linux层可以通过getprop和setprop去读写属性值。其实都是同一个东西。

在andorid框架中,SystemProperties来源于包android.os.SystemProperties;在framework中或者系统源码应用中可以随意使用。因为SystemProperties是一个隐藏类,所以在第三方应用中想使用SystemProperties通常使用反射。

一般来说实际开发中会写一个SystemProperties类,具体的get和set方法通过反射来实现。

public final class SystemProperties {

    public static String get(String property, String defaultValue) {
        try {
            Class clazz = Class.forName("android.os.SystemProperties");
            Method getter = clazz.getDeclaredMethod("get", String.class);
            String value = (String) getter.invoke(null, property);
            if (!TextUtils.isEmpty(value)) {
                return value;
            }
        } catch (Exception e) {
            Log.d("SystemProperties", "Unable to read system properties");
        }
        return defaultValue;
    }


    public static void set(String property, String value) {
        try {
            Class clazz = Class.forName("android.os.SystemProperties");
            Method setter = clazz.getDeclaredMethod("set", String.class);
            setter.invoke(null, property,value);

        } catch (Exception e) {
            Log.d("SystemProperties", "Unable to read system properties");
        }
    }
}

只需要调用SystemProperties.get()和SystemProperties.set()就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值