通过Android的反射机制实现系统属性的设置和获取

/**
 * 比较版本号,判断是否已进行版本更新.
 * 已更新则关闭adb.
 */
private void compareUIVersion() {
    String curUIVersion = Build.VERSION.INCREMENTAL;
    String dbUIVersion = "";
    Cursor cursor = this.getContentResolver().query(Uri.parse(GeneralCPConstants.CONTENT_URI),
            null, GeneralCPConstants.NAME + "='" + GeneralCPConstants.STARTIMES_UI_VERSION + "'", null, null);
    if (cursor == null || cursor.getCount() == 0) {//若数据库中还未有该记录,则设置adb开关.
        setAdbProperty("none");
    } else {
        if (cursor.moveToNext()) {
            dbUIVersion = cursor.getString(cursor.getColumnIndex(GeneralCPConstants.VALUE));
            if (!(dbUIVersion.equalsIgnoreCase(curUIVersion))) {
                setAdbProperty("none");
            }
        }
    }
}

private void setAdbProperty(String value) {
    PropertyUtils.set("persist.sys.usb.config", value);
    
        //这个persist.sys.usb.config 中adb 的配置是在alps/build/tools/post_process_props.py 中根据ro.debuggable = 1 or 0 来设置,1 就是开启adb, 0 即关闭adb debug. 而这个ro.debuggable 也是在alps/build/core/main.mk 中设置,和2.3 修改类似
        //不过您这样打开之后,对于user 版本adb shell 开启的还是shell 权限,而不是root 权限,如果您需要root 权限,需要再改一下system/core/adb/adb.c 里面的should_drop_privileges() 这个函数,在#ifndef ALLOW_ADBD_ROOT 时return 0; 而不是return 1; 即可。
}
 
 

//通过Android的反射机制实现系统属性的设置和获取.
//android.os.SystemProperties 提供了获取和设置系统属性的方法,但是这个类被隐藏了,应用开发时无法直接访问,可以通过反射的机制进行操作。
public class PropertyUtils {
    private static volatile Method set = null;
    private static volatile Method get = null;

    public static void set(String prop, String value) {

        try {
            if (null == set) {
                synchronized (PropertyUtils.class) {
                    if (null == set) {
                        Class<?> cls = Class.forName("android.os.SystemProperties");
                        set = cls.getDeclaredMethod("set", new Class<?>[]{String.class, String.class});
                    }
                }
            }
            set.invoke(null, new Object[]{prop, value});
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }


    public static String get(String prop, String defaultvalue) {
        String value = defaultvalue;
        try {
            if (null == get) {
                synchronized (PropertyUtils.class) {
                    if (null == get) {
                        Class<?> cls = Class.forName("android.os.SystemProperties");
                        get = cls.getDeclaredMethod("get", new Class<?>[]{String.class, String.class});
                    }
                }
            }
            value = (String) (get.invoke(null, new Object[]{prop, defaultvalue}));
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return value;
    }
}

猜你喜欢

转载自blog.csdn.net/u014748504/article/details/79814735
今日推荐