Java Examples for android.os.SystemProperties

The following java examples will help you to understand the usage of android.os.SystemProperties. These source code samples are taken from different open source projects.

Example 1
Project: meetup-client-master  File: SystemProperties.java View source code
public static long getLong(String s, long l) {
    if (sGetLongMethod == null) {
        return 100L;
    } else {
        try {
            Object aobj[] = new Object[2];
            aobj[0] = s;
            aobj[1] = Long.valueOf(100L);
            return ((Long) sGetLongMethod.invoke(null, aobj)).longValue();
        } catch (Exception exception) {
            Log.e("SystemProperties", "get error", exception);
            return 100L;
        }
    }
}
Example 2
Project: ABPlayer-master  File: SystemPropertiesProxy.java View source code
/**
	 * Get the value for the given key.
	 * 
	 * @return an empty string if the key isn't found
	 * @throws IllegalArgumentException if the key exceeds 32 characters
	 */
public static String get(String key) throws IllegalArgumentException {
    String ret = "";
    try {
        Class<?> SystemProperties = Class.forName("android.os.SystemProperties");
        //Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = { String.class };
        Method get = SystemProperties.getMethod("get", paramTypes);
        //Parameters
        Object[] params = { key };
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        ret = "";
    }
    return ret;
}
Example 3
Project: AirPlay-Receiver-on-Android-master  File: SystemPropertiesProxy.java View source code
/**
	 * Get the value for the given key.
	 * 
	 * @return an empty string if the key isn't found
	 * @throws IllegalArgumentException if the key exceeds 32 characters
	 */
public static String get(String key) throws IllegalArgumentException {
    String ret = "";
    try {
        Class<?> SystemProperties = Class.forName("android.os.SystemProperties");
        //Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = { String.class };
        Method get = SystemProperties.getMethod("get", paramTypes);
        //Parameters
        Object[] params = { key };
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        ret = "";
    }
    return ret;
}
Example 4
Project: ZI-master  File: SystemPropertiesProxy.java View source code
/**
	 * Get the value for the given key.
	 * 
	 * @return an empty string if the key isn't found
	 * @throws IllegalArgumentException if the key exceeds 32 characters
	 */
public static String get(String key) throws IllegalArgumentException {
    String ret = "";
    try {
        Class<?> SystemProperties = Class.forName("android.os.SystemProperties");
        //Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = { String.class };
        Method get = SystemProperties.getMethod("get", paramTypes);
        //Parameters
        Object[] params = { key };
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        ret = "";
    }
    return ret;
}
Example 5
Project: rootbeer-master  File: Utils.java View source code
/**
     * In Development - an idea of ours was to check the if selinux is enforcing - this could be disabled for some rooting apps
     * Checking for selinux mode
     *
     * @return true if selinux enabled
     */
public static boolean isSelinuxFlagInEnabled() {
    String selinux = null;
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        selinux = (String) get.invoke(c, "ro.build.selinux");
    } catch (Exception ignored) {
    }
    return "1".equals(selinux) ? true : false;
}
Example 6
Project: ZjDroid-master  File: Utility.java View source code
public static int getApiLevel() {
    try {
        Class<?> mClassType = Class.forName("android.os.SystemProperties");
        Method mGetIntMethod = mClassType.getDeclaredMethod("getInt", String.class, int.class);
        mGetIntMethod.setAccessible(true);
        return (Integer) mGetIntMethod.invoke(null, "ro.build.version.sdk", 14);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return 14;
}
Example 7
Project: android-sdk-sources-for-api-level-23-master  File: EntropyMixer.java View source code
/**
     * Add additional information to the kernel entropy pool.  The
     * information isn't necessarily "random", but that's ok.  Even
     * sending non-random information to {@code /dev/urandom} is useful
     * because, while it doesn't increase the "quality" of the entropy pool,
     * it mixes more bits into the pool, which gives us a higher degree
     * of uncertainty in the generated randomness.  Like nature, writes to
     * the random device can only cause the quality of the entropy in the
     * kernel to stay the same or increase.
     *
     * <p>For maximum effect, we try to target information which varies
     * on a per-device basis, and is not easily observable to an
     * attacker.
     */
private void addDeviceSpecificEntropy() {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new FileOutputStream(randomDevice));
        out.println("Copyright (C) 2009 The Android Open Source Project");
        out.println("All Your Randomness Are Belong To Us");
        out.println(START_TIME);
        out.println(START_NANOTIME);
        out.println(SystemProperties.get("ro.serialno"));
        out.println(SystemProperties.get("ro.bootmode"));
        out.println(SystemProperties.get("ro.baseband"));
        out.println(SystemProperties.get("ro.carrier"));
        out.println(SystemProperties.get("ro.bootloader"));
        out.println(SystemProperties.get("ro.hardware"));
        out.println(SystemProperties.get("ro.revision"));
        out.println(SystemProperties.get("ro.build.fingerprint"));
        out.println(new Object().hashCode());
        out.println(System.currentTimeMillis());
        out.println(System.nanoTime());
    } catch (IOException e) {
        Slog.w(TAG, "Unable to add device specific data to the entropy pool", e);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
Example 8
Project: android-visualizer-master  File: SystemPropertiesProxy.java View source code
public static Boolean getBoolean(ClassLoader cl, String key, boolean def) throws IllegalArgumentException {
    Boolean ret = def;
    try {
        @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties");
        // Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[2];
        paramTypes[0] = String.class;
        paramTypes[1] = boolean.class;
        @SuppressWarnings("unchecked") Method getBoolean = SystemProperties.getMethod("getBoolean", paramTypes);
        // Parameters
        Object[] params = new Object[2];
        params[0] = new String(key);
        params[1] = Boolean.valueOf(def);
        ret = (Boolean) getBoolean.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        Log.e(TAG, "getBoolean(context, key: " + key + ", def:" + def + ")", e);
        ret = def;
    }
    return ret;
}
Example 9
Project: ImmersionBar-master  File: OSUtils.java View source code
private static String getSystemProperty(String key, String defaultValue) {
    try {
        Class<?> clz = Class.forName("android.os.SystemProperties");
        Method get = clz.getMethod("get", String.class, String.class);
        return (String) get.invoke(clz, key, defaultValue);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return defaultValue;
}
Example 10
Project: android-device-identification-master  File: SystemPropertiesProxy.java View source code
/**
     * Get the value for the given key.
     *
     * @param context an Android constant (to retrieve system services)
     * @param key     the key to lookup
     * @return an empty string if the key isn't found
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
public static String get(Context context, String key) throws IllegalArgumentException {
    String ret = "";
    try {
        ClassLoader cl = context.getClassLoader();
        @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties");
        //Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[1];
        paramTypes[0] = String.class;
        Method get = SystemProperties.getMethod("get", paramTypes);
        //Parameters
        Object[] params = new Object[1];
        params[0] = new String(key);
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        ret = "";
    }
    return ret;
}
Example 11
Project: APKreator-master  File: SystemPropertiesReflection.java View source code
/**
     * Get the value for the given key.
     *
     * @return an empty string if the key isn't found
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
public static String get(Context context, String key) throws IllegalArgumentException {
    String ret = "";
    try {
        ClassLoader cl = context.getClassLoader();
        @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties");
        //Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[1];
        paramTypes[0] = String.class;
        Method get = SystemProperties.getMethod("get", paramTypes);
        //Parameters
        Object[] params = new Object[1];
        params[0] = new String(key);
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        ret = "";
    }
    return ret;
}
Example 12
Project: APKreatorWebsite-master  File: SystemPropertiesReflection.java View source code
/**
     * Get the value for the given key.
     *
     * @return an empty string if the key isn't found
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
public static String get(Context context, String key) throws IllegalArgumentException {
    String ret = "";
    try {
        ClassLoader cl = context.getClassLoader();
        @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties");
        //Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[1];
        paramTypes[0] = String.class;
        Method get = SystemProperties.getMethod("get", paramTypes);
        //Parameters
        Object[] params = new Object[1];
        params[0] = new String(key);
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        ret = "";
    }
    return ret;
}
Example 13
Project: Pimp_my_Z1-master  File: SystemPropertiesReflection.java View source code
/**
     * Get the value for the given key.
     *
     * @return an empty string if the key isn't found
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
public static String get(Context context, String key) throws IllegalArgumentException {
    String ret = "";
    try {
        ClassLoader cl = context.getClassLoader();
        @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties");
        //Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[1];
        paramTypes[0] = String.class;
        Method get = SystemProperties.getMethod("get", paramTypes);
        //Parameters
        Object[] params = new Object[1];
        params[0] = new String(key);
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        ret = "";
    }
    return ret;
}
Example 14
Project: Android-IMSI-Catcher-Detector-master  File: SystemPropertiesReflection.java View source code
/**
     * Get the value for the given key.
     *
     * @return an empty string if the key isn't found
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
public static String get(Context context, String key) throws IllegalArgumentException {
    String ret;
    try {
        ClassLoader cl = context.getClassLoader();
        Class<?> SystemProperties = cl.loadClass("android.os.SystemProperties");
        //Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[1];
        paramTypes[0] = String.class;
        Method get = SystemProperties.getMethod("get", paramTypes);
        //Parameters
        Object[] params = new Object[1];
        params[0] = key;
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iae) {
        log.error(iae.getMessage(), iae);
        throw iae;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        ret = "";
    }
    return ret;
}
Example 15
Project: androiddevice.info-master  File: SystemProperty.java View source code
public String getOrThrow(String key) throws NoSuchPropertyException {
    try {
        ClassLoader classLoader = mContext.getClassLoader();
        Class SystemProperties = classLoader.loadClass("android.os.SystemProperties");
        Method methodGet = SystemProperties.getMethod("get", String.class);
        return (String) methodGet.invoke(SystemProperties, key);
    } catch (ClassNotFoundException e) {
        throw new NoSuchPropertyException(e);
    } catch (NoSuchMethodException e) {
        throw new NoSuchPropertyException(e);
    } catch (InvocationTargetException e) {
        throw new NoSuchPropertyException(e);
    } catch (IllegalAccessException e) {
        throw new NoSuchPropertyException(e);
    }
}
Example 16
Project: SPD8810GA-master  File: OtaStartupReceiver.java View source code
/**
     * On devices that provide a phone initialization wizard (such as Google Setup Wizard), we 
     * allow delaying CDMA OTA setup so it can be done in a single wizard. The wizard is responsible
     * for (1) disabling itself once it has been run and/or (2) setting the 'device_provisioned' 
     * flag to something non-zero and (3) calling the OTA Setup with the action below.
     * 
     * NB: Typical phone initialization wizards will install themselves as the homescreen
     * (category "android.intent.category.HOME") with a priority higher than the default.  
     * The wizard should set 'device_provisioned' when it completes, disable itself with the
     * PackageManager.setComponentEnabledSetting() and then start home screen.
     * 
     * @return true if setup will be handled by wizard, false if it should be done now.
     */
private boolean shouldPostpone(Context context) {
    Intent intent = new Intent("android.intent.action.DEVICE_INITIALIZATION_WIZARD");
    ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    boolean provisioned = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
    String mode = SystemProperties.get("ro.setupwizard.mode", "REQUIRED");
    boolean runningSetupWizard = "REQUIRED".equals(mode) || "OPTIONAL".equals(mode);
    if (DBG) {
        Log.v(TAG, "resolvInfo = " + resolveInfo + ", provisioned = " + provisioned + ", runningSetupWizard = " + runningSetupWizard);
    }
    return resolveInfo != null && !provisioned && runningSetupWizard;
}
Example 17
Project: android-vts-master  File: SystemUtils.java View source code
//https://stackoverflow.com/questions/2641111/where-is-android-os-systemproperties
/**
     * Get the value for the given key.
     * @return an empty string if the key isn't found
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
public static String propertyGet(Context context, String key) throws IllegalArgumentException {
    String ret = "";
    try {
        ClassLoader cl = context.getClassLoader();
        @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties");
        //Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[1];
        paramTypes[0] = String.class;
        Method get = SystemProperties.getMethod("get", paramTypes);
        //Parameters
        Object[] params = new Object[1];
        params[0] = new String(key);
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        ret = "";
    }
    return ret;
}
Example 18
Project: android-smsmms-master  File: SystemPropertiesProxy.java View source code
/**
     * Get the value for the given key.
     *
     * @return an empty string if the key isn't found
     * @throws IllegalArgumentException if the key exceeds 32 characters
     */
public static String get(Context context, String key) throws IllegalArgumentException {
    String ret = "";
    try {
        ClassLoader cl = context.getClassLoader();
        @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties");
        //Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[1];
        paramTypes[0] = String.class;
        Method get = SystemProperties.getMethod("get", paramTypes);
        //Parameters
        Object[] params = new Object[1];
        params[0] = new String(key);
        ret = (String) get.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        ret = "";
    }
    return ret;
}
Example 19
Project: android_packages_apps_Roadrunner-master  File: StringUtils.java View source code
public static String maskAccountInfo(String str) {
    String ret = str;
    String serial = "";
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        serial = (String) get.invoke(c, "ro.serialno");
    } catch (Exception ignored) {
    }
    Matcher email = emailPattern.matcher(str);
    if (email.find()) {
        String strName = email.group(2);
        try {
            // generate some long noise
            byte[] bytesOfSerial = serial.getBytes("UTF-8");
            MessageDigest mdSha = MessageDigest.getInstance("SHA-256");
            byte[] theShaDigest = mdSha.digest(bytesOfSerial);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < theShaDigest.length; ++i) {
                sb.append(Integer.toHexString((theShaDigest[i] & 0xFF) | 0x100).substring(1, 3));
            }
            serial = sb.toString();
            byte[] bytesOfMessage = strName.concat(serial).getBytes("UTF-8");
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] thedigest = md.digest(bytesOfMessage);
            sb = new StringBuffer();
            for (int i = 0; i < thedigest.length; ++i) {
                sb.append(Integer.toHexString((thedigest[i] & 0xFF) | 0x100).substring(1, 3));
            }
            ret = email.group(1) + " " + sb.toString() + "@" + email.group(3) + email.group(4);
        } catch (Exception e) {
            Log.e(TAG, "An error occured: " + e.getMessage());
        }
    } else {
        Matcher account = accountnamePattern.matcher(str);
        if (account.find()) {
            String strName = account.group(2);
            try {
                byte[] bytesOfMessage = strName.getBytes("UTF-8");
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] thedigest = md.digest(bytesOfMessage);
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < thedigest.length; ++i) {
                    sb.append(Integer.toHexString((thedigest[i] & 0xFF) | 0x100).substring(1, 3));
                }
                ret = account.group(1) + sb.toString() + account.group(3);
            } catch (Exception e) {
                Log.e(TAG, "An error occured: " + e.getMessage());
            }
        }
    }
    return ret;
}
Example 20
Project: BetterBatteryStats-master  File: StringUtils.java View source code
public static String maskAccountInfo(String str) {
    String ret = str;
    String serial = "";
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        serial = (String) get.invoke(c, "ro.serialno");
    } catch (Exception ignored) {
    }
    Matcher email = emailPattern.matcher(str);
    if (email.find()) {
        String strName = email.group(2);
        try {
            // generate some long noise
            byte[] bytesOfSerial = serial.getBytes("UTF-8");
            MessageDigest mdSha = MessageDigest.getInstance("SHA-256");
            byte[] theShaDigest = mdSha.digest(bytesOfSerial);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < theShaDigest.length; ++i) {
                sb.append(Integer.toHexString((theShaDigest[i] & 0xFF) | 0x100).substring(1, 3));
            }
            serial = sb.toString();
            byte[] bytesOfMessage = strName.concat(serial).getBytes("UTF-8");
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] thedigest = md.digest(bytesOfMessage);
            sb = new StringBuffer();
            for (int i = 0; i < thedigest.length; ++i) {
                sb.append(Integer.toHexString((thedigest[i] & 0xFF) | 0x100).substring(1, 3));
            }
            ret = email.group(1) + sb.toString() + "@" + email.group(3) + email.group(4);
        } catch (Exception e) {
            Log.e(TAG, "An error occured: " + e.getMessage());
        }
    } else {
        Matcher account = accountnamePattern.matcher(str);
        if (account.find()) {
            String strName = account.group(2);
            try {
                byte[] bytesOfMessage = strName.getBytes("UTF-8");
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] thedigest = md.digest(bytesOfMessage);
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < thedigest.length; ++i) {
                    sb.append(Integer.toHexString((thedigest[i] & 0xFF) | 0x100).substring(1, 3));
                }
                ret = account.group(1) + sb.toString() + account.group(3);
            } catch (Exception e) {
                Log.e(TAG, "An error occured: " + e.getMessage());
            }
        }
    }
    return ret;
}
Example 21
Project: core-android-master  File: HelloWorldActivity.java View source code
/**
     * Returns the Android system property with the given name.
     */
private String getSystemProperty(String propertyName) throws Exception {
    // We're using reflection, because this Android API is private.
    // DexGuard will encrypt the strings for us (see dexguard-project.txt).
    Class clazz = Class.forName("android.os.SystemProperties");
    return (String) clazz.getMethod("get", new Class[] { String.class }).invoke(clazz, new Object[] { propertyName });
}
Example 22
Project: Performance-Tweaker-master  File: StringUtils.java View source code
public static String maskAccountInfo(String str) {
    String ret = str;
    String serial = "";
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        serial = (String) get.invoke(c, "ro.serialno");
    } catch (Exception ignored) {
    }
    Matcher email = emailPattern.matcher(str);
    if (email.find()) {
        String strName = email.group(2);
        try {
            // generate some long noise
            byte[] bytesOfSerial = serial.getBytes("UTF-8");
            MessageDigest mdSha = MessageDigest.getInstance("SHA-256");
            byte[] theShaDigest = mdSha.digest(bytesOfSerial);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < theShaDigest.length; ++i) {
                sb.append(Integer.toHexString((theShaDigest[i] & 0xFF) | 0x100).substring(1, 3));
            }
            serial = sb.toString();
            byte[] bytesOfMessage = strName.concat(serial).getBytes("UTF-8");
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] thedigest = md.digest(bytesOfMessage);
            sb = new StringBuffer();
            for (int i = 0; i < thedigest.length; ++i) {
                sb.append(Integer.toHexString((thedigest[i] & 0xFF) | 0x100).substring(1, 3));
            }
            ret = email.group(1) + sb.toString() + "@" + email.group(3) + email.group(4);
        } catch (Exception e) {
            Log.e(TAG, "An error occured: " + e.getMessage());
        }
    } else {
        Matcher account = accountnamePattern.matcher(str);
        if (account.find()) {
            String strName = account.group(2);
            try {
                byte[] bytesOfMessage = strName.getBytes("UTF-8");
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] thedigest = md.digest(bytesOfMessage);
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < thedigest.length; ++i) {
                    sb.append(Integer.toHexString((thedigest[i] & 0xFF) | 0x100).substring(1, 3));
                }
                ret = account.group(1) + sb.toString() + account.group(3);
            } catch (Exception e) {
                Log.e(TAG, "An error occured: " + e.getMessage());
            }
        }
    }
    return ret;
}
Example 23
Project: logback-android-master  File: SystemPropertiesProxy.java View source code
/**
   * Sets the classloader to lookup the class for android.os.SystemProperties
   *
   * @param cl desired classloader
   * @throws ClassNotFoundException android.os.SystemProperties class not found
   * @throws SecurityException security manager does not allow class loading
   * @throws NoSuchMethodException get/getBoolean method does not exist
   */
public void setClassLoader(ClassLoader cl) throws ClassNotFoundException, SecurityException, NoSuchMethodException {
    if (cl == null)
        cl = this.getClass().getClassLoader();
    SystemProperties = cl.loadClass("android.os.SystemProperties");
    getString = SystemProperties.getMethod("get", new Class[] { String.class, String.class });
    getBoolean = SystemProperties.getMethod("getBoolean", new Class[] { String.class, boolean.class });
}
Example 24
Project: androidMobileDeviceManager-master  File: UserAgentProvider.java View source code
@Override
public String get() {
    if (userAgent == null) {
        synchronized (UserAgentProvider.class) {
            if (userAgent == null) {
                userAgent = String.format("%s/%s (Android %s; %s %s / %s %s; %s)", APP_NAME, info.versionName, Build.VERSION.RELEASE, Strings.capitalize(Build.MANUFACTURER), Strings.capitalize(Build.DEVICE), Strings.capitalize(Build.BRAND), Strings.capitalize(Build.MODEL), Strings.capitalize(telephonyManager == null ? "not-found" : telephonyManager.getSimOperatorName()));
                final ArrayList<String> params = new ArrayList<String>();
                // Determine if this app was a preloaded app
                params.add("preload=" + ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1));
                params.add("locale=" + Locale.getDefault());
                // http://stackoverflow.com/questions/2641111/where-is-android-os-systemproperties
                try {
                    final Class SystemProperties = classLoader.loadClass("android.os.SystemProperties");
                    final Method get = SystemProperties.getMethod("get", String.class);
                    params.add("clientidbase=" + get.invoke(SystemProperties, "ro.com.google.clientidbase"));
                } catch (Exception ignored) {
                    Ln.d(ignored);
                }
                if (params.size() > 0)
                    userAgent += "[" + Strings.join(";", params) + "]";
            }
        }
    }
    return userAgent;
}
Example 25
Project: android-15-master  File: EntropyService.java View source code
/**
     * Add additional information to the kernel entropy pool.  The
     * information isn't necessarily "random", but that's ok.  Even
     * sending non-random information to {@code /dev/urandom} is useful
     * because, while it doesn't increase the "quality" of the entropy pool,
     * it mixes more bits into the pool, which gives us a higher degree
     * of uncertainty in the generated randomness.  Like nature, writes to
     * the random device can only cause the quality of the entropy in the
     * kernel to stay the same or increase.
     *
     * <p>For maximum effect, we try to target information which varies
     * on a per-device basis, and is not easily observable to an
     * attacker.
     */
private void addDeviceSpecificEntropy() {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new FileOutputStream(randomDevice));
        out.println("Copyright (C) 2009 The Android Open Source Project");
        out.println("All Your Randomness Are Belong To Us");
        out.println(START_TIME);
        out.println(START_NANOTIME);
        out.println(SystemProperties.get("ro.serialno"));
        out.println(SystemProperties.get("ro.bootmode"));
        out.println(SystemProperties.get("ro.baseband"));
        out.println(SystemProperties.get("ro.carrier"));
        out.println(SystemProperties.get("ro.bootloader"));
        out.println(SystemProperties.get("ro.hardware"));
        out.println(SystemProperties.get("ro.revision"));
        out.println(new Object().hashCode());
        out.println(System.currentTimeMillis());
        out.println(System.nanoTime());
    } catch (IOException e) {
        Slog.w(TAG, "Unable to add device specific data to the entropy pool", e);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
Example 26
Project: Android-Cookbook-Examples-master  File: MainActivity.java View source code
@Override
protected void onResume() {
    super.onResume();
    // Get "Device Serial Number". The Android SystemProperties is apparently not for public use,
    // as it exists on-device but is NOT exposed in the SDK, so treat with a grain of salt!
    String serialNumber = "unknown";
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class, String.class);
        serialNumber = (String) get.invoke(c, "ro.serialno", serialNumber);
    } catch (Exception e) {
        Log.e(TAG, "Failed to get serial number", e);
    }
    ((TextView) findViewById(R.id.serial_number)).setText(serialNumber);
    // Get "Android ID". According to the JavaDoc:
    // "A 64-bit number (as a hex string) that is 
    // randomly generated on the device's first boot 
    // and should remain constant for the lifetime 
    // of the device. (The value may change if a 
    // factory reset is performed on the device.)"
    String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
    ((TextView) findViewById(R.id.android_id)).setText(androidId);
    // Get the mobile device id (IMEI or similar) if any
    String imei = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    ((TextView) findViewById(R.id.imei)).setText(imei);
}
Example 27
Project: AndroidN-ify-master  File: RomUtils.java View source code
// Call only from UI
@SuppressLint("CommitPrefEdits")
private static void checkRom() {
    if (sPrefs.contains("rom"))
        return;
    String aicpVersion = SystemProperties.get("ro.aicp.version", "");
    if (!aicpVersion.equals("")) {
        sPrefs.edit().putString("rom", "aicp").commit();
        return;
    }
    int cmSdkVersion = SystemProperties.getInt("ro.cm.build.version.plat.sdk", 0);
    if (cmSdkVersion != 0) {
        sPrefs.edit().putString("rom", "cm").commit();
        return;
    }
    sPrefs.edit().putString("rom", "aosp").commit();
}
Example 28
Project: android_frameworks_base-master  File: EntropyMixer.java View source code
/**
     * Add additional information to the kernel entropy pool.  The
     * information isn't necessarily "random", but that's ok.  Even
     * sending non-random information to {@code /dev/urandom} is useful
     * because, while it doesn't increase the "quality" of the entropy pool,
     * it mixes more bits into the pool, which gives us a higher degree
     * of uncertainty in the generated randomness.  Like nature, writes to
     * the random device can only cause the quality of the entropy in the
     * kernel to stay the same or increase.
     *
     * <p>For maximum effect, we try to target information which varies
     * on a per-device basis, and is not easily observable to an
     * attacker.
     */
private void addDeviceSpecificEntropy() {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new FileOutputStream(randomDevice));
        out.println("Copyright (C) 2009 The Android Open Source Project");
        out.println("All Your Randomness Are Belong To Us");
        out.println(START_TIME);
        out.println(START_NANOTIME);
        out.println(SystemProperties.get("ro.serialno"));
        out.println(SystemProperties.get("ro.bootmode"));
        out.println(SystemProperties.get("ro.baseband"));
        out.println(SystemProperties.get("ro.carrier"));
        out.println(SystemProperties.get("ro.bootloader"));
        out.println(SystemProperties.get("ro.hardware"));
        out.println(SystemProperties.get("ro.revision"));
        out.println(SystemProperties.get("ro.build.fingerprint"));
        out.println(new Object().hashCode());
        out.println(System.currentTimeMillis());
        out.println(System.nanoTime());
    } catch (IOException e) {
        Slog.w(TAG, "Unable to add device specific data to the entropy pool", e);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
Example 29
Project: android_frameworks_base_telephony-master  File: PhoneFactory.java View source code
/**
     * FIXME replace this with some other way of making these
     * instances
     */
public static void makeDefaultPhone(Context context) {
    synchronized (Phone.class) {
        if (!sMadeDefaults) {
            sLooper = Looper.myLooper();
            sContext = context;
            if (sLooper == null) {
                throw new RuntimeException("PhoneFactory.makeDefaultPhone must be called from Looper thread");
            }
            int retryCount = 0;
            for (; ; ) {
                boolean hasException = false;
                retryCount++;
                try {
                    // use UNIX domain socket to
                    // prevent subsequent initialization
                    new LocalServerSocket("com.android.internal.telephony");
                } catch (java.io.IOException ex) {
                    hasException = true;
                }
                if (!hasException) {
                    break;
                } else if (retryCount > SOCKET_OPEN_MAX_RETRY) {
                    throw new RuntimeException("PhoneFactory probably already running");
                } else {
                    try {
                        Thread.sleep(SOCKET_OPEN_RETRY_MILLIS);
                    } catch (InterruptedException er) {
                    }
                }
            }
            sPhoneNotifier = new DefaultPhoneNotifier();
            //Get preferredNetworkMode from Settings.System
            int networkMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.PREFERRED_NETWORK_MODE, preferredNetworkMode);
            Log.i(LOG_TAG, "Network Mode set to " + Integer.toString(networkMode));
            //Get preferredNetworkMode from Settings.System
            int cdmaSubscription = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.PREFERRED_CDMA_SUBSCRIPTION, preferredCdmaSubscription);
            Log.i(LOG_TAG, "Cdma Subscription set to " + Integer.toString(cdmaSubscription));
            //reads the system properties and makes commandsinterface
            String sRILClassname = SystemProperties.get("ro.telephony.ril_class");
            Log.i(LOG_TAG, "RILClassname is " + sRILClassname);
            if ("samsung".equals(sRILClassname)) {
                Log.i(LOG_TAG, "Using Samsung RIL");
                sCommandsInterface = new SamsungRIL(context, networkMode, cdmaSubscription);
            } else if ("htc".equals(sRILClassname)) {
                Log.i(LOG_TAG, "Using HTC RIL");
                sCommandsInterface = new HTCRIL(context, networkMode, cdmaSubscription);
            } else if ("lgestar".equals(sRILClassname)) {
                Log.i(LOG_TAG, "Using LGE Star RIL");
                sCommandsInterface = new LGEStarRIL(context, networkMode, cdmaSubscription);
            } else if ("semc".equals(sRILClassname)) {
                Log.i(LOG_TAG, "Using Semc RIL");
                sCommandsInterface = new SemcRIL(context, networkMode, cdmaSubscription);
            } else if ("lgeqcom".equals(sRILClassname)) {
                Log.i(LOG_TAG, "Using LGE Qualcomm RIL");
                sCommandsInterface = new LGEQualcommRIL(context, networkMode, cdmaSubscription);
            } else if ("mototegra".equals(sRILClassname)) {
                Log.i(LOG_TAG, "Using Motorola Tegra2 RIL");
                sCommandsInterface = new MotoTegraRIL(context, networkMode, cdmaSubscription);
            } else {
                sCommandsInterface = new RIL(context, networkMode, cdmaSubscription);
            }
            int phoneType = getPhoneType(networkMode);
            if (phoneType == Phone.PHONE_TYPE_GSM) {
                Log.i(LOG_TAG, "Creating GSMPhone");
                sProxyPhone = new PhoneProxy(new GSMPhone(context, sCommandsInterface, sPhoneNotifier));
            } else if (phoneType == Phone.PHONE_TYPE_CDMA) {
                Log.i(LOG_TAG, "Creating CDMAPhone");
                sProxyPhone = new PhoneProxy(new CDMAPhone(context, sCommandsInterface, sPhoneNotifier));
            }
            sMadeDefaults = true;
        }
    }
}
Example 30
Project: anti-emulator-master  File: Utilities.java View source code
/**
     * Method to reflectively invoke the SystemProperties.get command - which is the equivalent to the adb shell getProp
     * command.
     * 
     * @param context
     *            A {@link Context} object used to get the proper ClassLoader (just needs to be Application Context
     *            object)
     * @param property
     *            A {@code String} object for the property to retrieve.
     * @return {@code String} value of the property requested.
     */
public static String getProp(Context context, String property) {
    try {
        ClassLoader classLoader = context.getClassLoader();
        Class<?> systemProperties = classLoader.loadClass("android.os.SystemProperties");
        Method get = systemProperties.getMethod("get", String.class);
        Object[] params = new Object[1];
        params[0] = new String(property);
        return (String) get.invoke(systemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception exception) {
        throw null;
    }
}
Example 31
Project: folio100_frameworks_base-master  File: EntropyService.java View source code
/**
     * Add additional information to the kernel entropy pool.  The
     * information isn't necessarily "random", but that's ok.  Even
     * sending non-random information to {@code /dev/urandom} is useful
     * because, while it doesn't increase the "quality" of the entropy pool,
     * it mixes more bits into the pool, which gives us a higher degree
     * of uncertainty in the generated randomness.  Like nature, writes to
     * the random device can only cause the quality of the entropy in the
     * kernel to stay the same or increase.
     *
     * <p>For maximum effect, we try to target information which varies
     * on a per-device basis, and is not easily observable to an
     * attacker.
     */
private void addDeviceSpecificEntropy() {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new FileOutputStream(randomDevice));
        out.println("Copyright (C) 2009 The Android Open Source Project");
        out.println("All Your Randomness Are Belong To Us");
        out.println(START_TIME);
        out.println(START_NANOTIME);
        out.println(SystemProperties.get("ro.serialno"));
        out.println(SystemProperties.get("ro.bootmode"));
        out.println(SystemProperties.get("ro.baseband"));
        out.println(SystemProperties.get("ro.carrier"));
        out.println(SystemProperties.get("ro.bootloader"));
        out.println(SystemProperties.get("ro.hardware"));
        out.println(SystemProperties.get("ro.revision"));
        out.println(System.currentTimeMillis());
        out.println(System.nanoTime());
    } catch (IOException e) {
        Slog.w(TAG, "Unable to add device specific data to the entropy pool", e);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
Example 32
Project: frameworks_base_disabled-master  File: PhoneFactory.java View source code
/**
     * FIXME replace this with some other way of making these
     * instances
     */
public static void makeDefaultPhone(Context context) {
    synchronized (Phone.class) {
        if (!sMadeDefaults) {
            sLooper = Looper.myLooper();
            sContext = context;
            if (sLooper == null) {
                throw new RuntimeException("PhoneFactory.makeDefaultPhone must be called from Looper thread");
            }
            int retryCount = 0;
            for (; ; ) {
                boolean hasException = false;
                retryCount++;
                try {
                    // use UNIX domain socket to
                    // prevent subsequent initialization
                    new LocalServerSocket("com.android.internal.telephony");
                } catch (java.io.IOException ex) {
                    hasException = true;
                }
                if (!hasException) {
                    break;
                } else if (retryCount > SOCKET_OPEN_MAX_RETRY) {
                    throw new RuntimeException("PhoneFactory probably already running");
                } else {
                    try {
                        Thread.sleep(SOCKET_OPEN_RETRY_MILLIS);
                    } catch (InterruptedException er) {
                    }
                }
            }
            sPhoneNotifier = new DefaultPhoneNotifier();
            // Get preferred network mode
            int preferredNetworkMode = RILConstants.PREFERRED_NETWORK_MODE;
            if (BaseCommands.getLteOnCdmaModeStatic() == Phone.LTE_ON_CDMA_TRUE) {
                preferredNetworkMode = Phone.NT_MODE_GLOBAL;
            }
            if (BaseCommands.getLteOnGsmModeStatic() != 0) {
                preferredNetworkMode = Phone.NT_MODE_LTE_GSM_WCDMA;
            }
            int networkMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.PREFERRED_NETWORK_MODE, preferredNetworkMode);
            Log.i(LOG_TAG, "Network Mode set to " + Integer.toString(networkMode));
            //Get cdmaSubscription mode from Settings.Secure
            int cdmaSubscription;
            cdmaSubscription = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.CDMA_SUBSCRIPTION_MODE, preferredCdmaSubscription);
            Log.i(LOG_TAG, "Cdma Subscription set to " + cdmaSubscription);
            //reads the system properties and makes commandsinterface
            String sRILClassname = SystemProperties.get("ro.telephony.ril_class", "RIL");
            Log.i(LOG_TAG, "RILClassname is " + sRILClassname);
            // Use reflection to construct the RIL class (defaults to RIL)
            try {
                Class<?> classDefinition = Class.forName("com.android.internal.telephony." + sRILClassname);
                Constructor<?> constructor = classDefinition.getConstructor(new Class[] { Context.class, int.class, int.class });
                sCommandsInterface = (RIL) constructor.newInstance(new Object[] { context, networkMode, cdmaSubscription });
            } catch (Exception e) {
                Log.wtf(LOG_TAG, "Unable to construct command interface", e);
                throw new RuntimeException(e);
            }
            int phoneType = getPhoneType(networkMode);
            if (phoneType == Phone.PHONE_TYPE_GSM) {
                Log.i(LOG_TAG, "Creating GSMPhone");
                sProxyPhone = new PhoneProxy(new GSMPhone(context, sCommandsInterface, sPhoneNotifier));
            } else if (phoneType == Phone.PHONE_TYPE_CDMA) {
                switch(BaseCommands.getLteOnCdmaModeStatic()) {
                    case Phone.LTE_ON_CDMA_TRUE:
                        Log.i(LOG_TAG, "Creating CDMALTEPhone");
                        sProxyPhone = new PhoneProxy(new CDMALTEPhone(context, sCommandsInterface, sPhoneNotifier));
                        break;
                    case Phone.LTE_ON_CDMA_FALSE:
                    default:
                        Log.i(LOG_TAG, "Creating CDMAPhone");
                        sProxyPhone = new PhoneProxy(new CDMAPhone(context, sCommandsInterface, sPhoneNotifier));
                        break;
                }
            }
            sMadeDefaults = true;
        }
    }
}
Example 33
Project: ify-master  File: RomUtils.java View source code
// Call only from UI
@SuppressLint("CommitPrefEdits")
private static void checkRom() {
    if (sPrefs.contains("rom"))
        return;
    String aicpVersion = SystemProperties.get("ro.aicp.version", "");
    if (!aicpVersion.equals("")) {
        sPrefs.edit().putString("rom", "aicp").commit();
        return;
    }
    int cmSdkVersion = SystemProperties.getInt("ro.cm.build.version.plat.sdk", 0);
    if (cmSdkVersion != 0) {
        sPrefs.edit().putString("rom", "cm").commit();
        return;
    }
    sPrefs.edit().putString("rom", "aosp").commit();
}
Example 34
Project: m2e-master  File: MainActivity.java View source code
@Override
protected void onResume() {
    super.onResume();
    // Get "Device Serial Number". The Android SystemProperties is apparently not for public use,
    // as it exists on-device but is NOT exposed in the SDK, so treat with a grain of salt!
    String serialNumber = "unknown";
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class, String.class);
        serialNumber = (String) get.invoke(c, "ro.serialno", serialNumber);
    } catch (Exception e) {
        Log.e(TAG, "Failed to get serial number", e);
    }
    ((TextView) findViewById(R.id.serial_number)).setText(serialNumber);
    // Get "Android ID". According to the JavaDoc:
    // "A 64-bit number (as a hex string) that is 
    // randomly generated on the device's first boot 
    // and should remain constant for the lifetime 
    // of the device. (The value may change if a 
    // factory reset is performed on the device.)"
    String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
    ((TextView) findViewById(R.id.android_id)).setText(androidId);
    // Get the mobile device id (IMEI or similar) if any
    String imei = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    ((TextView) findViewById(R.id.imei)).setText(imei);
}
Example 35
Project: MvpApp-master  File: NavUtils.java View source code
/**
     * 检测是�有虚拟键
     * @param context
     * @return
     */
public static boolean checkDeviceHasNavigationBar(Context context) {
    boolean hasNavigationBar = false;
    Resources rs = context.getResources();
    int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = rs.getBoolean(id);
    }
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method m = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
    }
    return hasNavigationBar;
}
Example 36
Project: MyLibrary-master  File: DeviceUtil.java View source code
// TODO: ggg 2017/3/22 : 8.0上�在支�SystemProperties.get("net.hostname")
public static String getHostName2() {
    try {
        return Reflect.load("android.os.SystemProperties").method("get", String.class, String.class).call("net.hostname", Build.UNKNOWN);
    } catch (Reflect.ReflectException e) {
        StringBuilder sb = new StringBuilder();
        sb.append(Build.MANUFACTURER).append("_").append(Build.MODEL);
        return sb.toString();
    }
//        try {
//            // TODO: ggg 2017/3/22 : 8.0上�在支�SystemProperties.get("net.hostname")
//            Class clazz = Class.forName("android.os.SystemProperties");
//            Method get = clazz.getDeclaredMethod("get", String.class);
//            get.setAccessible(true);
//            return get.invoke(null, "net.hostname").toString();
//        } catch (ClassNotFoundException e) {
//            logger.debug(e.getMessage(), e);
//        } catch (NoSuchMethodException e) {
//            logger.debug(e.getMessage(), e);
//        } catch (IllegalAccessException e) {
//            logger.debug(e.getMessage(), e);
//        } catch (InvocationTargetException e) {
//            logger.debug(e.getMessage(), e);
//        }
//
//        StringBuilder sb = new StringBuilder();
//        sb.append(Build.MANUFACTURER).append("_").append(Build.MODEL);
//        return sb.toString();
}
Example 37
Project: OneClickAndroid-master  File: OneClickReportingIntentService.java View source code
@Override
protected void onHandleIntent(Intent intent) {
    // send individual events in background
    Bundle bundle = intent.getExtras();
    if (!bundle.isEmpty()) {
        if (mTracker == null) {
            Log.w(TAG, "Tracker missing");
            return;
        }
        String category = bundle.getString(Fields.EVENT_CATEGORY);
        String action = bundle.getString(Fields.EVENT_ACTION);
        HitBuilders.EventBuilder eventBuilder = new HitBuilders.EventBuilder(category, action);
        eventBuilder.setCustomDimension(1, SystemProperties.get("ro.product.brand"));
        eventBuilder.setCustomDimension(2, SystemProperties.get("ro.product.device"));
        eventBuilder.setCustomDimension(3, SystemProperties.get("ro.product.model"));
        eventBuilder.setCustomDimension(4, SystemProperties.get("ro.product.name"));
        eventBuilder.setCustomDimension(5, SystemProperties.get("ro.product.board"));
        eventBuilder.setCustomDimension(6, SystemProperties.get("ro.product.cpu.abi"));
        if (bundle.containsKey(Fields.EVENT_LABEL)) {
            eventBuilder.setLabel(bundle.getString(Fields.EVENT_LABEL));
        }
        if (bundle.containsKey(Fields.EVENT_VALUE)) {
            eventBuilder.setValue(bundle.getLong(Fields.EVENT_VALUE));
        }
        Log.w(TAG, "onHandleIntent/" + category + "/" + action + "/" + bundle.getString(Fields.EVENT_LABEL) + "/" + bundle.getLong(Fields.EVENT_VALUE));
        mTracker.send(eventBuilder.build());
    }
}
Example 38
Project: platform_frameworks_base-master  File: SELinuxPolicyInstallReceiver.java View source code
private void applyUpdate() throws IOException, ErrnoException {
    Slog.i(TAG, "Applying SELinux policy");
    File backup = new File(updateDir.getParentFile(), "backup");
    File current = new File(updateDir.getParentFile(), "current");
    File tmp = new File(updateDir.getParentFile(), "tmp");
    if (current.exists()) {
        deleteRecursive(backup);
        Os.rename(current.getPath(), backup.getPath());
    }
    try {
        Os.rename(tmp.getPath(), current.getPath());
        SystemProperties.set("selinux.reload_policy", "1");
    } catch (ErrnoException e) {
        Slog.e(TAG, "Could not update selinux policy: ", e);
        if (backup.exists()) {
            Os.rename(backup.getPath(), current.getPath());
        }
    }
}
Example 39
Project: PonyMusic-master  File: SystemUtils.java View source code
private static String getSystemProperty(String key) {
    try {
        Class<?> classType = Class.forName("android.os.SystemProperties");
        Method getMethod = classType.getDeclaredMethod("get", String.class);
        return (String) getMethod.invoke(classType, key);
    } catch (Throwable th) {
        th.printStackTrace();
    }
    return null;
}
Example 40
Project: property-db-master  File: SamplingProfilerService.java View source code
@Override
public void onChange(boolean selfChange) {
    Integer samplingProfilerMs = Settings.Global.getInt(mContentResolver, Settings.Global.SAMPLING_PROFILER_MS, 0);
    // setting this secure property will start or stop sampling profiler,
    // as well as adjust the the time between taking snapshots.
    SystemProperties.set("persist.sys.profiler_ms", samplingProfilerMs.toString());
}
Example 41
Project: WS171-frameworks-base-master  File: PhoneFactory.java View source code
/**
     * FIXME replace this with some other way of making these
     * instances
     */
public static void makeDefaultPhones(Context context) {
    synchronized (Phone.class) {
        if (!sMadeDefaults) {
            sLooper = Looper.myLooper();
            if (sLooper == null) {
                throw new RuntimeException("PhoneFactory.makeDefaultPhones must be called from Looper thread");
            }
            int retryCount = 0;
            for (; ; ) {
                boolean hasException = false;
                retryCount++;
                try {
                    // use UNIX domain socket to
                    // prevent subsequent initialization
                    new LocalServerSocket("com.android.internal.telephony");
                } catch (java.io.IOException ex) {
                    hasException = true;
                }
                if (!hasException) {
                    break;
                } else if (retryCount > SOCKET_OPEN_MAX_RETRY) {
                    throw new RuntimeException("PhoneFactory probably already running");
                } else {
                    try {
                        Thread.sleep(SOCKET_OPEN_RETRY_MILLIS);
                    } catch (InterruptedException er) {
                    }
                }
            }
            sPhoneNotifier = new DefaultPhoneNotifier();
            if ((SystemProperties.get("ro.radio.noril", "")).equals("")) {
                useNewRIL(context);
            } else {
                GSMPhone phone;
                phone = new GSMPhone(context, new SimulatedCommands(), sPhoneNotifier);
                registerPhone(phone);
            }
            sMadeDefaults = true;
        }
    }
}
Example 42
Project: Yasuo-master  File: UIUtils.java View source code
public static boolean hasNavigationBar(Context activity) {
    boolean hasNavigationBar = false;
    Resources resources = activity.getResources();
    int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = resources.getBoolean(id);
    }
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method method = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) method.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
    }
    return hasNavigationBar;
}
Example 43
Project: ZhihuDaily-master  File: UIUtils.java View source code
public static boolean hasNavigationBar(Context activity) {
    boolean hasNavigationBar = false;
    Resources resources = activity.getResources();
    int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = resources.getBoolean(id);
    }
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method method = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) method.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
        L.e("UIUtiles", e.toString());
    }
    return hasNavigationBar;
}
Example 44
Project: android_tv_metro-master  File: MiTVSystem.java View source code
public static String getProperty(Context con, String key) {
    //reflect call system properties
    Class osSystem = null;
    try {
        osSystem = Class.forName("android.os.SystemProperties");
        Method getDeviceIDMethod = osSystem.getMethod("get", new Class[] { String.class });
        String tv2deviceid = (String) getDeviceIDMethod.invoke(osSystem, new Object[] { key });
        if (tv2deviceid != null && tv2deviceid.length() > 0) {
            Log.d("DeviceHelper", key + " = " + tv2deviceid);
            return tv2deviceid;
        }
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    return "";
}
Example 45
Project: dexposed-master  File: DeviceCheck.java View source code
private static String getCurrentRuntimeValue() {
    try {
        Class<?> systemProperties = Class.forName("android.os.SystemProperties");
        try {
            Method get = systemProperties.getMethod("get", String.class, String.class);
            if (get == null) {
                return "WTF?!";
            }
            try {
                final String value = (String) get.invoke(systemProperties, SELECT_RUNTIME_PROPERTY, /* Assuming default is */
                "Dalvik");
                if (LIB_DALVIK.equals(value)) {
                    return "Dalvik";
                } else if (LIB_ART.equals(value)) {
                    return "ART";
                } else if (LIB_ART_D.equals(value)) {
                    return "ART debug build";
                }
                return value;
            } catch (IllegalAccessException e) {
                return "IllegalAccessException";
            } catch (IllegalArgumentException e) {
                return "IllegalArgumentException";
            } catch (InvocationTargetException e) {
                return "InvocationTargetException";
            }
        } catch (NoSuchMethodException e) {
            return "SystemProperties.get(String key, String def) method is not found";
        }
    } catch (ClassNotFoundException e) {
        return "SystemProperties class is not found";
    }
}
Example 46
Project: test4XXX-master  File: Compat.java View source code
@SuppressLint("DefaultLocale")
private static boolean isYunOS() {
    Log.d("euler", "Compat, isYunOS");
    String version = null;
    String vmName = null;
    try {
        Method m = Class.forName("android.os.SystemProperties").getMethod("get", String.class);
        version = (String) m.invoke(null, "ro.yunos.version");
        vmName = (String) m.invoke(null, "java.vm.name");
    } catch (Exception e) {
    }
    if ((vmName != null && vmName.toLowerCase().contains("lemur")) || (version != null && version.trim().length() > 0)) {
        return true;
    } else {
        return false;
    }
}
Example 47
Project: android-openslmediaplayer-master  File: NuPlayerDetector.java View source code
public static Boolean getBoolean(ClassLoader cl, String key, boolean def) throws IllegalArgumentException {
    Boolean ret = def;
    try {
        @SuppressWarnings("rawtypes") Class SystemProperties = cl.loadClass("android.os.SystemProperties");
        // Parameters Types
        @SuppressWarnings("rawtypes") Class[] paramTypes = new Class[2];
        paramTypes[0] = String.class;
        paramTypes[1] = boolean.class;
        @SuppressWarnings("unchecked") Method getBoolean = SystemProperties.getMethod("getBoolean", paramTypes);
        // Parameters
        Object[] params = new Object[2];
        params[0] = new String(key);
        params[1] = Boolean.valueOf(def);
        ret = (Boolean) getBoolean.invoke(SystemProperties, params);
    } catch (IllegalArgumentException iAE) {
        throw iAE;
    } catch (Exception e) {
        Log.e(TAG, "getBoolean(context, key: " + key + ", def:" + def + ")", e);
        ret = def;
    }
    return ret;
}
Example 48
Project: BGAWeiBo-Android-master  File: UIUtils.java View source code
public static boolean checkDeviceHasNavigationBar(Context context) {
    boolean hasNavigationBar = false;
    Resources rs = context.getResources();
    int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = rs.getBoolean(id);
    }
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method m = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
    }
    return hasNavigationBar;
}
Example 49
Project: commonJar-master  File: JScreenTool.java View source code
/**
     * caller must add <android:sharedUserId="android.uid.system"> in AndroidManifest.xml
     * 
     * @param ctx
     * @return screenshot bitmap
     */
public static Bitmap takeScreenshot(Context ctx) {
    WindowManager mWindowManager = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
    Display mDisplay = mWindowManager.getDefaultDisplay();
    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    mDisplay.getRealMetrics(mDisplayMetrics);
    Matrix mDisplayMatrix = new Matrix();
    float[] dims = { mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels };
    int value = mDisplay.getRotation();
    String hwRotation = SystemProperties.get("ro.sf.hwrotation", "0");
    if (hwRotation.equals("270") || hwRotation.equals("90")) {
        value = (value + 3) % 4;
    }
    float degrees = getDegreesForRotation(value);
    boolean requiresRotation = (degrees > 0);
    if (requiresRotation) {
        // Get the dimensions of the device in its native orientation
        mDisplayMatrix.reset();
        mDisplayMatrix.preRotate(-degrees);
        mDisplayMatrix.mapPoints(dims);
        dims[0] = Math.abs(dims[0]);
        dims[1] = Math.abs(dims[1]);
    }
    // Surface.screenshot((int) dims[0], (int) dims[1]);
    Bitmap mScreenBitmap = null;
    if (requiresRotation && mScreenBitmap != null) {
        // Rotate the screenshot to the current orientation
        Bitmap ss = Bitmap.createBitmap(mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(ss);
        c.translate(ss.getWidth() / 2, ss.getHeight() / 2);
        c.rotate(degrees);
        c.translate(-dims[0] / 2, -dims[1] / 2);
        c.drawBitmap(mScreenBitmap, 0, 0, null);
        c.setBitmap(null);
        mScreenBitmap = ss;
    }
    if (mScreenBitmap == null) {
        return null;
    }
    // Optimizations
    mScreenBitmap.setHasAlpha(false);
    mScreenBitmap.prepareToDraw();
    return mScreenBitmap;
}
Example 50
Project: MediaNote-Android-master  File: UIUtil.java View source code
public static boolean checkDeviceHasNavigationBar(Context context) {
    boolean hasNavigationBar = false;
    Resources rs = context.getResources();
    int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = rs.getBoolean(id);
    }
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method m = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
    }
    return hasNavigationBar;
}
Example 51
Project: packages_apps_settings-master  File: SimSelectNotification.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    final SubscriptionManager subscriptionManager = SubscriptionManager.from(context);
    final int numSlots = telephonyManager.getSimCount();
    // or User selection of fallback user preference is disabled.
    if (numSlots < 2 || !Utils.isDeviceProvisioned(context) || !SystemProperties.getBoolean("persist.radio.aosp_usr_pref_sel", false)) {
        Log.d(TAG, " no of slots " + numSlots + " provision = " + Utils.isDeviceProvisioned(context));
        return;
    }
    // Cancel any previous notifications
    cancelNotification(context);
    // If sim state is not ABSENT or LOADED then ignore
    String simStatus = intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE);
    if (!(IccCardConstants.INTENT_VALUE_ICC_ABSENT.equals(simStatus) || IccCardConstants.INTENT_VALUE_ICC_LOADED.equals(simStatus))) {
        Log.d(TAG, "sim state is not Absent or Loaded");
        return;
    } else {
        Log.d(TAG, "simstatus = " + simStatus);
    }
    int state;
    for (int i = 0; i < numSlots; i++) {
        state = telephonyManager.getSimState(i);
        if (!(state == TelephonyManager.SIM_STATE_ABSENT || state == TelephonyManager.SIM_STATE_READY || state == TelephonyManager.SIM_STATE_UNKNOWN)) {
            Log.d(TAG, "All sims not in valid state yet");
            return;
        }
    }
    List<SubscriptionInfo> sil = subscriptionManager.getActiveSubscriptionInfoList();
    if (sil == null || sil.size() < 1) {
        Log.d(TAG, "Subscription list is empty");
        return;
    }
    // Clear defaults for any subscriptions which no longer exist
    subscriptionManager.clearDefaultsForInactiveSubIds();
    boolean dataSelected = SubscriptionManager.isUsableSubIdValue(SubscriptionManager.getDefaultDataSubscriptionId());
    boolean smsSelected = SubscriptionManager.isUsableSubIdValue(SubscriptionManager.getDefaultSmsSubscriptionId());
    // If data and sms defaults are selected, dont show notification (Calls default is optional)
    if (dataSelected && smsSelected) {
        Log.d(TAG, "Data & SMS default sims are selected. No notification");
        return;
    }
    // Create a notification to tell the user that some defaults are missing
    createNotification(context);
    if (sil.size() == 1) {
        // If there is only one subscription, ask if user wants to use if for everything
        Intent newIntent = new Intent(context, SimDialogActivity.class);
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        newIntent.putExtra(SimDialogActivity.DIALOG_TYPE_KEY, SimDialogActivity.PREFERRED_PICK);
        newIntent.putExtra(SimDialogActivity.PREFERRED_SIM, sil.get(0).getSimSlotIndex());
        context.startActivity(newIntent);
    } else if (!dataSelected) {
        // If there are mulitple, ensure they pick default data
        Intent newIntent = new Intent(context, SimDialogActivity.class);
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        newIntent.putExtra(SimDialogActivity.DIALOG_TYPE_KEY, SimDialogActivity.DATA_PICK);
        context.startActivity(newIntent);
    }
}
Example 52
Project: platform_packages_apps_settings-master  File: SettingsLicenseActivityTest.java View source code
@Test
public void testOnCreateWithValidHtmlFile() {
    SystemProperties.set("ro.config.license_path", "/system/etc/NOTICE.html.gz");
    doReturn(true).when(mActivity).isFileValid(any());
    mActivity.onCreate(null);
    final Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("file:///system/etc/NOTICE.html.gz"), "text/html");
    intent.putExtra(Intent.EXTRA_TITLE, mActivity.getString(R.string.settings_license_activity_title));
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setPackage("com.android.htmlviewer");
    assertEqualIntents(shadowOf(mApplication).getNextStartedActivity(), intent);
}
Example 53
Project: Project-M-1-master  File: BootReceiver.java View source code
@Override
public void onReceive(Context ctx, Intent intent) {
    if (SystemProperties.getBoolean(CPU_SETTINGS_PROP, false) == false && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
        SystemProperties.set(CPU_SETTINGS_PROP, "true");
        configureCPU(ctx);
    } else {
        SystemProperties.set(CPU_SETTINGS_PROP, "false");
    }
    if (SystemProperties.getBoolean(IOSCHED_SETTINGS_PROP, false) == false && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
        SystemProperties.set(IOSCHED_SETTINGS_PROP, "true");
        configureIOSched(ctx);
    } else {
        SystemProperties.set(IOSCHED_SETTINGS_PROP, "false");
    }
    if (Utils.fileExists(MemoryManagement.KSM_RUN_FILE)) {
        if (SystemProperties.getBoolean(KSM_SETTINGS_PROP, false) == false && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            SystemProperties.set(KSM_SETTINGS_PROP, "true");
            configureKSM(ctx);
        } else {
            SystemProperties.set(KSM_SETTINGS_PROP, "false");
        }
    }
}
Example 54
Project: UPMiss-master  File: SysTool.java View source code
/**
     * This device's SN
     *
     * @return SerialNumber
     */
public static String getSerialNumber() {
    String serialNumber = android.os.Build.SERIAL;
    if ((serialNumber == null || serialNumber.length() == 0 || serialNumber.contains("unknown"))) {
        String[] keys = new String[] { "ro.boot.serialno", "ro.serialno" };
        for (String key : keys) {
            try {
                Method systemProperties_get = Class.forName("android.os.SystemProperties").getMethod("get", String.class);
                serialNumber = (String) systemProperties_get.invoke(null, key);
                if (serialNumber != null && serialNumber.length() > 0 && !serialNumber.contains("unknown"))
                    break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return serialNumber;
}
Example 55
Project: XobotOS-master  File: TestFramerateView.java View source code
private void registerTime(long now_us) {
    long longFrameTime_ms = Integer.parseInt(SystemProperties.get("debug.longframe_ms", "16"));
    long elapsedTime_us = now_us - mLastTime_us;
    float fps = 1000000.f / elapsedTime_us;
    if (mLastTime_us > 0 && elapsedTime_us > longFrameTime_ms * 1000) {
        Log.v(TAG, "Long frame: " + elapsedTime_us / 1000.f + " ms (" + fps + " fps)");
        if (mNumShortFramesElapsed > 0) {
            Log.v(TAG, "  Short frames since last long frame: " + mNumShortFramesElapsed);
            mNumShortFramesElapsed = 0;
        }
    } else {
        ++mNumShortFramesElapsed;
    }
    mLastTime_us = now_us;
}
Example 56
Project: FactoryTest-master  File: SystemUtils.java View source code
/**
	 * 
	 * ����������ȡϵͳ����
	 * @param field
	 * @return
	 */
public static String getSystemProperties(String field) {
    String platform = null;
    try {
        Class<?> classType = Class.forName("android.os.SystemProperties");
        Method getMethod = classType.getDeclaredMethod("get", new Class<?>[] { String.class });
        platform = (String) getMethod.invoke(classType, new Object[] { field });
    } catch (Exception e) {
        e.printStackTrace();
    }
    return platform;
}
Example 57
Project: OMzen-master  File: Utils.java View source code
// Get the value for the given key
// @param key: key to lookup
// @return null if the key isn't found
public static String get(String key) {
    String ret;
    try {
        Class<?> classSystemProperties = findClass("android.os.SystemProperties", null);
        ret = (String) callStaticMethod(classSystemProperties, "get", key);
    } catch (Throwable t) {
        log("SystemProp.get failed: " + t.getMessage());
        ret = null;
    }
    return ret;
}
Example 58
Project: 2.3.3-Phone-Merge-master  File: EmergencyCallbackModeService.java View source code
/**
     * Start timer notification for Emergency Callback Mode
     */
private void startTimerNotification() {
    // Get Emergency Callback Mode timeout value
    long ecmTimeout = SystemProperties.getLong(TelephonyProperties.PROPERTY_ECM_EXIT_TIMER, DEFAULT_ECM_EXIT_TIMER_VALUE);
    // Show the notification
    showNotification(ecmTimeout);
    // Start countdown timer for the notification updates
    mTimer = new CountDownTimer(ecmTimeout, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            mTimeLeft = millisUntilFinished;
            EmergencyCallbackModeService.this.showNotification(millisUntilFinished);
        }

        @Override
        public void onFinish() {
        //Do nothing
        }
    }.start();
}
Example 59
Project: android_device_softwinner_cubieboard1-master  File: WirelessSettings.java View source code
/**
     * Invoked on each preference click in this hierarchy, overrides
     * PreferenceActivity's implementation.  Used to make sure we track the
     * preference click events.
     */
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    if (preference == mAirplaneModePreference && Boolean.parseBoolean(SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE))) {
        // In ECM mode launch ECM app dialog
        startActivityForResult(new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null), REQUEST_CODE_EXIT_ECM);
        return true;
    }
    // Let the intents be launched by the Preference manager
    return super.onPreferenceTreeClick(preferenceScreen, preference);
}
Example 60
Project: android_packages_apps-master  File: WirelessSettings.java View source code
/**
     * Invoked on each preference click in this hierarchy, overrides
     * PreferenceActivity's implementation.  Used to make sure we track the
     * preference click events.
     */
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    if (preference == mAirplaneModePreference && Boolean.parseBoolean(SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE))) {
        // In ECM mode launch ECM app dialog
        startActivityForResult(new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null), REQUEST_CODE_EXIT_ECM);
        return true;
    }
    // Let the intents be launched by the Preference manager
    return super.onPreferenceTreeClick(preferenceScreen, preference);
}
Example 61
Project: android_packages_apps_settings-master  File: WirelessSettings.java View source code
/**
     * Invoked on each preference click in this hierarchy, overrides
     * PreferenceActivity's implementation.  Used to make sure we track the
     * preference click events.
     */
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    if (preference == mAirplaneModePreference && Boolean.parseBoolean(SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE))) {
        // In ECM mode launch ECM app dialog
        startActivityForResult(new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null), REQUEST_CODE_EXIT_ECM);
        return true;
    }
    // Let the intents be launched by the Preference manager
    return false;
}
Example 62
Project: banya-master  File: ViewUtils.java View source code
// 获�是�存在NavigationBar:
public static boolean checkDeviceHasNavigationBar(Context context) {
    boolean hasNavigationBar = false;
    Resources rs = context.getResources();
    int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = rs.getBoolean(id);
    }
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method m = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
    }
    return hasNavigationBar;
}
Example 63
Project: BGASwipeBackLayout-Android-master  File: UIUtil.java View source code
private static boolean oldCheckDeviceHasNavigationBar(Activity activity) {
    boolean hasNavigationBar = false;
    Resources resources = activity.getResources();
    int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = resources.getBoolean(id);
    }
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method m = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
    }
    return hasNavigationBar;
}
Example 64
Project: Blur-Hello-World-Page-master  File: Utils.java View source code
public boolean hasNavBar() {
    try {
        Class c = Class.forName("android.os.SystemProperties");
        Method m = c.getDeclaredMethod("get", String.class);
        m.setAccessible(true);
        String result = (String) m.invoke(null, "qemu.hw.mainkeys");
        boolean hasNav = !("1".equals(result));
        return hasNav;
    } catch (Throwable e) {
        return true;
    }
}
Example 65
Project: DeskSMS-master  File: Helper.java View source code
@SuppressLint("NewApi")
public static String getSafeDeviceId(Context context) {
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String deviceId = tm.getDeviceId();
    if (deviceId == null) {
        String wifiInterface = SystemProperties.get("wifi.interface");
        try {
            if (Build.VERSION.SDK_INT < 9)
                throw new Exception();
            String wifiMac = new String(NetworkInterface.getByName(wifiInterface).getHardwareAddress());
            deviceId = wifiMac;
        } catch (Exception e) {
            deviceId = "000000000000";
        }
    }
    deviceId += context.getPackageName();
    String ret = digest(deviceId);
    return ret;
}
Example 66
Project: happy-dns-android-master  File: AndroidDnsServer.java View source code
// 1ms
public static InetAddress[] getByReflection() {
    try {
        Class<?> SystemProperties = Class.forName("android.os.SystemProperties");
        Method method = SystemProperties.getMethod("get", new Class<?>[] { String.class });
        ArrayList<InetAddress> servers = new ArrayList<InetAddress>(5);
        for (String propKey : new String[] { "net.dns1", "net.dns2", "net.dns3", "net.dns4" }) {
            String value = (String) method.invoke(null, propKey);
            if (value == null)
                continue;
            if (value.length() == 0)
                continue;
            InetAddress ip = InetAddress.getByName(value);
            if (ip == null)
                continue;
            value = ip.getHostAddress();
            if (value == null)
                continue;
            if (value.length() == 0)
                continue;
            if (servers.contains(ip))
                continue;
            servers.add(ip);
        }
        if (servers.size() > 0) {
            return servers.toArray(new InetAddress[servers.size()]);
        }
    } catch (Exception e) {
        Logger.getLogger("AndroidDnsServer").log(Level.WARNING, "Exception in findDNSByReflection", e);
    }
    return null;
}
Example 67
Project: new_test-master  File: WirelessSettings.java View source code
/**
     * Invoked on each preference click in this hierarchy, overrides
     * PreferenceActivity's implementation.  Used to make sure we track the
     * preference click events.
     */
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    if (preference == mAirplaneModePreference && Boolean.parseBoolean(SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE))) {
        // In ECM mode launch ECM app dialog
        startActivityForResult(new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null), REQUEST_CODE_EXIT_ECM);
        return true;
    }
    // Let the intents be launched by the Preference manager
    return false;
}
Example 68
Project: NIM_Android_Demo-master  File: SysInfoUtil.java View source code
private static final String getProp(Context context, String property) {
    try {
        ClassLoader cl = context.getClassLoader();
        Class<?> SystemProperties = cl.loadClass("android.os.SystemProperties");
        Method method = SystemProperties.getMethod("get", String.class);
        Object[] params = new Object[1];
        params[0] = property;
        return (String) method.invoke(SystemProperties, params);
    } catch (Exception e) {
        return null;
    }
}
Example 69
Project: packages_apps_ROMControl-master  File: HostnamePreference.java View source code
@Override
public void setText(String text) {
    if (text == null) {
        Log.e(TAG, "tried to set null hostname, request ignored");
        return;
    } else if (text.length() == 0) {
        Log.w(TAG, "setting empty hostname");
    } else {
        Log.i(TAG, "hostname has been set: " + text);
    }
    SystemProperties.set(PROP_HOSTNAME, text);
    persistHostname(text);
    setSummary(text);
}
Example 70
Project: Phone_eclair-master  File: OtaStartupReceiver.java View source code
/**
     * On devices that provide a phone initialization wizard (such as Google Setup Wizard), we 
     * allow delaying CDMA OTA setup so it can be done in a single wizard. The wizard is responsible
     * for (1) disabling itself once it has been run and/or (2) setting the 'device_provisioned' 
     * flag to something non-zero and (3) calling the OTA Setup with the action below.
     * 
     * NB: Typical phone initialization wizards will install themselves as the homescreen
     * (category "android.intent.category.HOME") with a priority higher than the default.  
     * The wizard should set 'device_provisioned' when it completes, disable itself with the
     * PackageManager.setComponentEnabledSetting() and then start home screen.
     * 
     * @return true if setup will be handled by wizard, false if it should be done now.
     */
private boolean shouldPostpone(Context context) {
    Intent intent = new Intent("android.intent.action.DEVICE_INITIALIZATION_WIZARD");
    ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    boolean provisioned = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
    String mode = SystemProperties.get("ro.setupwizard.mode", "REQUIRED");
    boolean runningSetupWizard = "REQUIRED".equals(mode) || "OPTIONAL".equals(mode);
    if (DBG) {
        Log.v(TAG, "resolvInfo = " + resolveInfo + ", provisioned = " + provisioned + ", runningSetupWizard = " + runningSetupWizard);
    }
    return resolveInfo != null && !provisioned && runningSetupWizard;
}
Example 71
Project: Phone_gingerbread-master  File: OtaStartupReceiver.java View source code
/**
     * On devices that provide a phone initialization wizard (such as Google Setup Wizard), we 
     * allow delaying CDMA OTA setup so it can be done in a single wizard. The wizard is responsible
     * for (1) disabling itself once it has been run and/or (2) setting the 'device_provisioned' 
     * flag to something non-zero and (3) calling the OTA Setup with the action below.
     * 
     * NB: Typical phone initialization wizards will install themselves as the homescreen
     * (category "android.intent.category.HOME") with a priority higher than the default.  
     * The wizard should set 'device_provisioned' when it completes, disable itself with the
     * PackageManager.setComponentEnabledSetting() and then start home screen.
     * 
     * @return true if setup will be handled by wizard, false if it should be done now.
     */
private boolean shouldPostpone(Context context) {
    Intent intent = new Intent("android.intent.action.DEVICE_INITIALIZATION_WIZARD");
    ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    boolean provisioned = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
    String mode = SystemProperties.get("ro.setupwizard.mode", "REQUIRED");
    boolean runningSetupWizard = "REQUIRED".equals(mode) || "OPTIONAL".equals(mode);
    if (DBG) {
        Log.v(TAG, "resolvInfo = " + resolveInfo + ", provisioned = " + provisioned + ", runningSetupWizard = " + runningSetupWizard);
    }
    return resolveInfo != null && !provisioned && runningSetupWizard;
}
Example 72
Project: PhotoNoter-master  File: AppCompat.java View source code
public static boolean hasNavigationBar(Context context) {
    boolean hasNavigationBar = false;
    Resources rs = context.getResources();
    int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = rs.getBoolean(id);
    }
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method m = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
        Log.wtf("AppCompat", e.getMessage());
    }
    return hasNavigationBar;
}
Example 73
Project: sawan-bar-master  File: OtaStartupReceiver.java View source code
/**
     * On devices that provide a phone initialization wizard (such as Google Setup Wizard), we 
     * allow delaying CDMA OTA setup so it can be done in a single wizard. The wizard is responsible
     * for (1) disabling itself once it has been run and/or (2) setting the 'device_provisioned' 
     * flag to something non-zero and (3) calling the OTA Setup with the action below.
     * 
     * NB: Typical phone initialization wizards will install themselves as the homescreen
     * (category "android.intent.category.HOME") with a priority higher than the default.  
     * The wizard should set 'device_provisioned' when it completes, disable itself with the
     * PackageManager.setComponentEnabledSetting() and then start home screen.
     * 
     * @return true if setup will be handled by wizard, false if it should be done now.
     */
private boolean shouldPostpone(Context context) {
    Intent intent = new Intent("android.intent.action.DEVICE_INITIALIZATION_WIZARD");
    ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    boolean provisioned = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
    String mode = SystemProperties.get("ro.setupwizard.mode", "REQUIRED");
    boolean runningSetupWizard = "REQUIRED".equals(mode) || "OPTIONAL".equals(mode);
    if (DBG) {
        Log.v(TAG, "resolvInfo = " + resolveInfo + ", provisioned = " + provisioned + ", runningSetupWizard = " + runningSetupWizard);
    }
    return resolveInfo != null && !provisioned && runningSetupWizard;
}
Example 74
Project: SearchPictureTool-master  File: Utils.java View source code
private static boolean checkDeviceHasNavigationBarAgain(Context context) {
    boolean hasNavigationBar = false;
    Resources rs = context.getResources();
    int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
    if (id > 0) {
        hasNavigationBar = rs.getBoolean(id);
    }
    try {
        Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
        Method m = systemPropertiesClass.getMethod("get", String.class);
        String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
        if ("1".equals(navBarOverride)) {
            hasNavigationBar = false;
        } else if ("0".equals(navBarOverride)) {
            hasNavigationBar = true;
        }
    } catch (Exception e) {
    }
    return hasNavigationBar;
}
Example 75
Project: STFService.apk-master  File: IdentityActivity.java View source code
private String getProperty(String name, String defaultValue) {
    try {
        Class<?> SystemProperties = Class.forName("android.os.SystemProperties");
        Method get = SystemProperties.getMethod("get", String.class, String.class);
        return (String) get.invoke(SystemProperties, name, defaultValue);
    } catch (ClassNotFoundException e) {
        Log.e(TAG, "Class.forName() failed", e);
        return defaultValue;
    } catch (NoSuchMethodException e) {
        Log.e(TAG, "getMethod() failed", e);
        return defaultValue;
    } catch (InvocationTargetException e) {
        Log.e(TAG, "invoke() failed", e);
        return defaultValue;
    } catch (IllegalAccessException e) {
        Log.e(TAG, "invoke() failed", e);
        return defaultValue;
    }
}
Example 76
Project: android-imf-ext-master  File: SSLCertificateSocketFactory.java View source code
private void validateSocket(SSLSocket sslSock, String destHost) throws IOException {
    if (Config.LOGV) {
        Log.v(LOG_TAG, "validateSocket() to host " + destHost);
    }
    String relaxSslCheck = SystemProperties.get("socket.relaxsslcheck");
    String secure = SystemProperties.get("ro.secure");
    // specifically requested.
    if ("0".equals(secure) && "yes".equals(relaxSslCheck)) {
        if (Config.LOGD) {
            Log.d(LOG_TAG, "sys prop socket.relaxsslcheck is set," + " ignoring invalid certs");
        }
        return;
    }
    Certificate[] certs = null;
    sslSock.setUseClientMode(true);
    sslSock.startHandshake();
    certs = sslSock.getSession().getPeerCertificates();
    // a CA we trust
    if (certs == null) {
        Log.e(LOG_TAG, "[SSLCertificateSocketFactory] no trusted root CA");
        throw new IOException("no trusted root CA");
    }
    if (Config.LOGV) {
        Log.v(LOG_TAG, "validateSocket # certs = " + certs.length);
    }
    if (!hasValidCertificateChain(certs)) {
        if (Config.LOGD) {
            Log.d(LOG_TAG, "validateSocket(): certificate untrusted!");
        }
        throw new IOException("Certificate untrusted");
    }
    X509Certificate lastChainCert = (X509Certificate) certs[0];
    if (!DomainNameChecker.match(lastChainCert, destHost)) {
        if (Config.LOGD) {
            Log.d(LOG_TAG, "validateSocket(): domain name check failed");
        }
        throw new IOException("Domain Name check failed");
    }
}
Example 77
Project: android-rcs-ims-stack-master  File: HttpsProvisioningUtils.java View source code
/**
     * Returns a system parameter
     * 
     * @param key Key parameter
     * @return Parameter value
     */
protected static String getSystemProperties(String key) {
    String value = null;
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        value = (String) get.invoke(c, key);
        return value;
    } catch (Exception e) {
        return HttpsProvisioningUtils.UNKNOWN;
    }
}
Example 78
Project: android_packages_apps_phone-master  File: EmergencyCallbackModeService.java View source code
/**
     * Start timer notification for Emergency Callback Mode
     */
private void startTimerNotification() {
    // Get Emergency Callback Mode timeout value
    long ecmTimeout = SystemProperties.getLong(TelephonyProperties.PROPERTY_ECM_EXIT_TIMER, DEFAULT_ECM_EXIT_TIMER_VALUE);
    // Show the notification
    showNotification(ecmTimeout);
    // Start countdown timer for the notification updates
    mTimer = new CountDownTimer(ecmTimeout, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            mTimeLeft = millisUntilFinished;
            EmergencyCallbackModeService.this.showNotification(millisUntilFinished);
        }

        @Override
        public void onFinish() {
        //Do nothing
        }
    }.start();
}
Example 79
Project: Brevent-master  File: SettingsFragment.java View source code
@Override
public void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    onShowDonationChanged();
    boolean adbRunning = SystemProperties.get("init.svc.adbd", Build.UNKNOWN).equals("running");
    Preference preference = getPreferenceScreen().findPreference("brevent_about_developer");
    if (adbRunning) {
        preference.setSummary(R.string.brevent_about_developer_adb);
    } else {
        preference.setSummary(null);
    }
    preference.setOnPreferenceClickListener(this);
}
Example 80
Project: cnAndroidDocs-master  File: EntropyMixer.java View source code
/**
     * Add additional information to the kernel entropy pool.  The
     * information isn't necessarily "random", but that's ok.  Even
     * sending non-random information to {@code /dev/urandom} is useful
     * because, while it doesn't increase the "quality" of the entropy pool,
     * it mixes more bits into the pool, which gives us a higher degree
     * of uncertainty in the generated randomness.  Like nature, writes to
     * the random device can only cause the quality of the entropy in the
     * kernel to stay the same or increase.
     *
     * <p>For maximum effect, we try to target information which varies
     * on a per-device basis, and is not easily observable to an
     * attacker.
     */
private void addDeviceSpecificEntropy() {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new FileOutputStream(randomDevice));
        out.println("Copyright (C) 2009 The Android Open Source Project");
        out.println("All Your Randomness Are Belong To Us");
        out.println(START_TIME);
        out.println(START_NANOTIME);
        out.println(SystemProperties.get("ro.serialno"));
        out.println(SystemProperties.get("ro.bootmode"));
        out.println(SystemProperties.get("ro.baseband"));
        out.println(SystemProperties.get("ro.carrier"));
        out.println(SystemProperties.get("ro.bootloader"));
        out.println(SystemProperties.get("ro.hardware"));
        out.println(SystemProperties.get("ro.revision"));
        out.println(new Object().hashCode());
        out.println(System.currentTimeMillis());
        out.println(System.nanoTime());
    } catch (IOException e) {
        Slog.w(TAG, "Unable to add device specific data to the entropy pool", e);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}
Example 81
Project: device_falcon_umts_kk-master  File: FmConfig.java View source code
/*
     * fmConfigure()
     * This method call v4l2 private controls to set regional settings for the
     * FM core
     */
protected static boolean fmConfigure(final int fd, final FmConfig configSettings) {
    int re;
    Log.v(TAG, "In fmConfigure");
    re = FmReceiverJNI.setControlNative(fd, V4L2_CID_PRIVATE_TAVARUA_EMPHASIS, configSettings.getEmphasis());
    re = FmReceiverJNI.setControlNative(fd, V4L2_CID_PRIVATE_TAVARUA_RDS_STD, configSettings.getRdsStd());
    re = FmReceiverJNI.setControlNative(fd, V4L2_CID_PRIVATE_TAVARUA_SPACING, configSettings.getChSpacing());
    boolean fmSrchAlg = SystemProperties.getBoolean("persist.fm.new.srch.algorithm", false);
    if (fmSrchAlg) {
        Log.v(TAG, "fmConfigure() : FM Srch Alg : NEW ");
        re = FmReceiverJNI.setControlNative(fd, V4L2_CID_PRIVATE_TAVARUA_SRCH_ALGORITHM, 1);
    } else {
        Log.v(TAG, "fmConfigure() : FM Srch Alg : OLD ");
        re = FmReceiverJNI.setControlNative(fd, V4L2_CID_PRIVATE_TAVARUA_SRCH_ALGORITHM, 0);
    }
    if (re < 0)
        return false;
    re = FmReceiverJNI.setBandNative(fd, configSettings.getLowerLimit(), configSettings.getUpperLimit());
    if (re < 0)
        return false;
    re = FmReceiverJNI.setControlNative(fd, V4L2_CID_PRIVATE_TAVARUA_REGION, configSettings.mRadioBand);
    /* setControlNative for V4L2_CID_PRIVATE_TAVARUA_REGION triggers the config change*/
    if (re < 0)
        return false;
    return true;
}
Example 82
Project: DouYu-master  File: DeviceUtil.java View source code
/**
     * 获得�列�
     * @return �列�
     */
public static String getSerialNum() {
    String serialNum = null;
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class, String.class);
        serialNum = (String) (get.invoke(c, "ro.serialno", "unknown"));
    } catch (Exception ignored) {
    }
    return serialNum;
}
Example 83
Project: Kollosal_Player-master  File: HWDecoderUtil.java View source code
private static String getSystemProperty(String key, String def) {
    try {
        final ClassLoader cl = ClassLoader.getSystemClassLoader();
        final Class<?> SystemProperties = cl.loadClass("android.os.SystemProperties");
        final Class<?>[] paramTypes = new Class[] { String.class, String.class };
        final Method get = SystemProperties.getMethod("get", paramTypes);
        final Object[] params = new Object[] { key, def };
        return (String) get.invoke(SystemProperties, params);
    } catch (Exception e) {
        return def;
    }
}
Example 84
Project: MobilSecurity-master  File: FetchData.java View source code
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String fetch_baseband_version() {
    String result = "";
    try {
        Class cl = Class.forName("android.os.SystemProperties");
        Object invoker = cl.newInstance();
        Method m = cl.getMethod("get", new Class[] { String.class, String.class });
        result = (String) m.invoke(invoker, new Object[] { "gsm.version.baseband", "no message" });
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
Example 85
Project: multiplevlc-master  File: HWDecoderUtil.java View source code
private static String getSystemProperty(String key, String def) {
    try {
        final ClassLoader cl = ClassLoader.getSystemClassLoader();
        final Class<?> SystemProperties = cl.loadClass("android.os.SystemProperties");
        final Class<?>[] paramTypes = new Class[] { String.class, String.class };
        final Method get = SystemProperties.getMethod("get", paramTypes);
        final Object[] params = new Object[] { key, def };
        return (String) get.invoke(SystemProperties, params);
    } catch (Exception e) {
        return def;
    }
}
Example 86
Project: Phone_froyo-master  File: OtaStartupReceiver.java View source code
/**
     * On devices that provide a phone initialization wizard (such as Google Setup Wizard), we 
     * allow delaying CDMA OTA setup so it can be done in a single wizard. The wizard is responsible
     * for (1) disabling itself once it has been run and/or (2) setting the 'device_provisioned' 
     * flag to something non-zero and (3) calling the OTA Setup with the action below.
     * 
     * NB: Typical phone initialization wizards will install themselves as the homescreen
     * (category "android.intent.category.HOME") with a priority higher than the default.  
     * The wizard should set 'device_provisioned' when it completes, disable itself with the
     * PackageManager.setComponentEnabledSetting() and then start home screen.
     * 
     * @return true if setup will be handled by wizard, false if it should be done now.
     */
private boolean shouldPostpone(Context context) {
    Intent intent = new Intent("android.intent.action.DEVICE_INITIALIZATION_WIZARD");
    ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    boolean provisioned = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
    String mode = SystemProperties.get("ro.setupwizard.mode", "REQUIRED");
    boolean runningSetupWizard = "REQUIRED".equals(mode) || "OPTIONAL".equals(mode);
    if (DBG) {
        Log.v(TAG, "resolvInfo = " + resolveInfo + ", provisioned = " + provisioned + ", runningSetupWizard = " + runningSetupWizard);
    }
    return resolveInfo != null && !provisioned && runningSetupWizard;
}
Example 87
Project: PJ-master  File: MainActivity.java View source code
public static String getProperty() {
    String property = "null";
    if (!"Xiaomi".equals(Build.MANUFACTURER)) {
        return property;
    }
    try {
        Class<?> spClazz = Class.forName("android.os.SystemProperties");
        Method method = spClazz.getDeclaredMethod("get", String.class, String.class);
        property = (String) method.invoke(spClazz, "ro.miui.ui.version.name", null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return property;
}
Example 88
Project: WS171-development-master  File: RadioIssueReport.java View source code
/**
     * @return a snapshot of phone state variables to report.
     */
private static Map<String, String> snapState() {
    Map<String, String> state = Maps.newHashMap();
    // Capture a bunch of system properties
    for (String property : SYSTEM_PROPERTIES) {
        String value = SystemProperties.get(property);
        state.put(property, SystemProperties.get(property));
    }
    Phone phone = PhoneFactory.getDefaultPhone();
    state.put("phone-data", phone.getDataConnectionState().toString());
    state.put("phone-service", phone.getServiceState().toString());
    state.put("phone-signal", String.valueOf(phone.getSignalStrengthASU()));
    state.put("phone-state", phone.getState().toString());
    try {
        state.put("radio-log", getRadioLog());
    } catch (IOException e) {
        Log.e(TAG, "Error reading radio log", e);
    }
    return state;
}
Example 89
Project: XieDaDeng-master  File: StorageNotification.java View source code
private void onStorageStateChangedAsync(String path, String oldState, String newState) {
    if (DEBUG)
        Log.i(TAG, String.format("Media {%s} state changed from {%s} -> {%s}", path, oldState, newState));
    if (newState.equals(Environment.MEDIA_SHARED)) {
        /*
             * Storage is now shared. Modify the UMS notification
             * for stopping UMS.
             */
        Intent intent = new Intent();
        if (orignal_support) {
            intent.setClass(mContext, com.android.systemui.usb.UsbStorageActivity.class);
        } else {
            intent.setComponent(new ComponentName("com.android.settings", "com.sprd.settings.SprdUsbSettings"));
        }
        PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
        setUsbStorageNotification(com.android.internal.R.string.usb_storage_stop_notification_title, com.android.internal.R.string.usb_storage_stop_notification_message, com.android.internal.R.drawable.stat_sys_warning, false, true, pi);
    } else if (newState.equals(Environment.MEDIA_CHECKING)) {
        /*
             * Storage is now checking. Update media notification and disable
             * UMS notification.
             */
        setMediaStorageNotification(com.android.internal.R.string.ext_media_checking_notification_title, com.android.internal.R.string.ext_media_checking_notification_message, com.android.internal.R.drawable.stat_notify_sdcard_prepare, true, false, null);
        updateUsbMassStorageNotification(false);
    } else if (newState.equals(Environment.MEDIA_MOUNTED)) {
        /*
             * Storage is now mounted. Dismiss any media notifications,
             * and enable UMS notification if connected.
             */
        setMediaStorageNotification(0, 0, 0, false, false, null);
        updateUsbMassStorageNotification(mUmsAvailable);
    } else if (newState.equals(Environment.MEDIA_UNMOUNTED)) {
        /*
             * Storage is now unmounted. We may have been unmounted
             * because the user is enabling/disabling UMS, in which case we don't
             * want to display the 'safe to unmount' notification.
             */
        if (!mStorageManager.isUsbMassStorageEnabled()) {
            if (oldState.equals(Environment.MEDIA_SHARED)) {
                /*
                     * The unmount was due to UMS being enabled. Dismiss any
                     * media notifications, and enable UMS notification if connected
                     */
                setMediaStorageNotification(0, 0, 0, false, false, null);
                updateUsbMassStorageNotification(mUmsAvailable);
            } else {
                /*
                     * Show safe to unmount media notification, and enable UMS
                     * notification if connected.
                     */
                if (Environment.isExternalStorageRemovable()) {
                    setMediaStorageNotification(com.android.internal.R.string.ext_media_safe_unmount_notification_title, com.android.internal.R.string.ext_media_safe_unmount_notification_message, com.android.internal.R.drawable.stat_notify_sdcard, true, true, null);
                } else {
                    // This device does not have removable storage, so
                    // don't tell the user they can remove it.
                    setMediaStorageNotification(0, 0, 0, false, false, null);
                }
                updateUsbMassStorageNotification(mUmsAvailable);
            }
        } else {
            /*
                 * The unmount was due to UMS being enabled. Dismiss any
                 * media notifications, and disable the UMS notification
                 */
            setMediaStorageNotification(0, 0, 0, false, false, null);
            updateUsbMassStorageNotification(false);
        }
    } else if (newState.equals(Environment.MEDIA_NOFS)) {
        /*
             * Storage has no filesystem. Show blank media notification,
             * and enable UMS notification if connected.
             */
        Intent intent = new Intent();
        intent.setClass(mContext, com.android.internal.app.ExternalMediaFormatActivity.class);
        PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
        setMediaStorageNotification(com.android.internal.R.string.ext_media_nofs_notification_title, com.android.internal.R.string.ext_media_nofs_notification_message, com.android.internal.R.drawable.stat_notify_sdcard_usb, true, false, pi);
        updateUsbMassStorageNotification(mUmsAvailable);
    } else if (newState.equals(Environment.MEDIA_UNMOUNTABLE)) {
        /*
             * Storage is corrupt. Show corrupt media notification,
             * and enable UMS notification if connected.
             */
        Intent intent = new Intent();
        intent.setClass(mContext, com.android.internal.app.ExternalMediaFormatActivity.class);
        PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent, 0);
        setMediaStorageNotification(com.android.internal.R.string.ext_media_unmountable_notification_title, com.android.internal.R.string.ext_media_unmountable_notification_message, com.android.internal.R.drawable.stat_notify_sdcard_usb, true, false, pi);
        updateUsbMassStorageNotification(mUmsAvailable);
    } else if (newState.equals(Environment.MEDIA_REMOVED)) {
        /*
             * Storage has been removed. Show nomedia media notification,
             * and disable UMS notification regardless of connection state.
             */
        if (android.os.SystemProperties.get("ro.project.customer_name").trim().equalsIgnoreCase("i-mobile")) {
        } else {
            setMediaStorageNotification(com.android.internal.R.string.ext_media_nomedia_notification_title, com.android.internal.R.string.ext_media_nomedia_notification_message, com.android.internal.R.drawable.stat_notify_sdcard_usb, true, false, null);
        }
        updateUsbMassStorageNotification(false);
    } else if (newState.equals(Environment.MEDIA_BAD_REMOVAL)) {
        /*
             * Storage has been removed unsafely. Show bad removal media notification,
             * and disable UMS notification regardless of connection state.
             */
        setMediaStorageNotification(com.android.internal.R.string.ext_media_badremoval_notification_title, com.android.internal.R.string.ext_media_badremoval_notification_message, com.android.internal.R.drawable.stat_sys_warning, true, true, null);
        updateUsbMassStorageNotification(false);
    } else {
        Log.w(TAG, String.format("Ignoring unknown state {%s}", newState));
    }
}
Example 90
Project: RocBrowser-master  File: TraceEvent.java View source code
/**
     * Calling this will cause enabled() to be updated to match that set on the native side.
     * The native library must be loaded before calling this method.
     */
public static void setEnabledToMatchNative() {
    boolean enabled = nativeTraceEnabled();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        try {
            Class<?> traceClass = Class.forName("android.os.Trace");
            long traceTagView = traceClass.getField("TRACE_TAG_VIEW").getLong(null);
            String propertyTraceTagEnableFlags = (String) traceClass.getField("PROPERTY_TRACE_TAG_ENABLEFLAGS").get(null);
            Class<?> systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method systemPropertiesGetLongMethod = systemPropertiesClass.getDeclaredMethod("getLong", String.class, Long.TYPE);
            long enabledFlags = (Long) systemPropertiesGetLongMethod.invoke(null, propertyTraceTagEnableFlags, 0);
            Log.d("TraceEvent", "New enabled flags: " + enabledFlags);
            if ((enabledFlags & traceTagView) != 0) {
                nativeStartATrace();
                enabled = true;
            } else {
                nativeStopATrace();
            }
        } catch (ClassNotFoundException e) {
            Log.e("TraceEvent", "setEnabledToMatchNative", e);
        } catch (NoSuchMethodException e) {
            Log.e("TraceEvent", "setEnabledToMatchNative", e);
        } catch (NoSuchFieldException e) {
            Log.e("TraceEvent", "setEnabledToMatchNative", e);
        } catch (IllegalArgumentException e) {
            Log.e("TraceEvent", "setEnabledToMatchNative", e);
        } catch (IllegalAccessException e) {
            Log.e("TraceEvent", "setEnabledToMatchNative", e);
        } catch (InvocationTargetException e) {
            Log.e("TraceEvent", "setEnabledToMatchNative", e);
        }
    }
    setEnabled(enabled);
}
Example 91
Project: ACDD-master  File: BundleLifecycleHandler.java View source code
private boolean isLewaOS() {
    try {
        return StringUtils.isNotEmpty((String) Class.forName("android.os.SystemProperties").getDeclaredMethod(ServicePermission.GET, new Class[] { String.class }).invoke(null, "ro.lewa.version"));
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
Example 92
Project: android-util-master  File: MiscUtils.java View source code
/**
     *
     * @param context  context
     * @return  SerialNumber
     */
public static String getSerialNumber(Context context) {
    String serial = null;
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        serial = (String) get.invoke(c, "ro.serialno");
        if (serial == null || serial.trim().length() <= 0) {
            TelephonyManager tManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            serial = tManager.getDeviceId();
        }
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
    return serial;
}
Example 93
Project: android-vpn-server-master  File: DaemonProxy.java View source code
void start() throws IOException {
    String svc = mName;
    Log.i(mTag, "Start VPN daemon: " + svc);
    SystemProperties.set(SVC_START_CMD, svc);
    if (!blockUntil(SVC_STATE_RUNNING, WAITING_TIME)) {
        throw new IOException("cannot start service: " + svc);
    } else {
        mControlSocket = createServiceSocket();
    }
}
Example 94
Project: androidrocks-master  File: ServiceActivateDeactivate.java View source code
public void onClick(View v) {
    //Fetching IMSI and UserID from MobeegalUser Table
    try {
        String[] col1 = { "IMSI" };
        Cursor c = myDB.query("MobeegalUser", col1, null, null, null, null, null);
        int imsi = c.getColumnIndexOrThrow("IMSI");
        int userID = c.getColumnIndexOrThrow("UserId");
        if (c != null) {
            if (c.isFirst()) {
                do {
                    imsiNumber = c.getString(imsi);
                    userIDstring = c.getString(userID);
                    results.add(userIDstring);
                    results.add(imsiNumber);
                } while (c.moveToNext());
            }
        }
        String res = results.toString();
        // First time registering and sending IMSI number to server
        String myIMSI = android.os.SystemProperties.get(TelephonyProperties.PROPERTY_SIM_OPERATOR_NUMERIC);
        if (myIMSI != imsiNumber) {
            String register = "register";
            String IMSI = "456957013123456";
            JSONStringer js = new JSONStringer();
            // old request         js.object().key("action").value(register).key("query").object().key("IMSI").value(IMSI).endObject();
            /* new request */
            js.object().key("action").value(register).key("group").value("Nokia").key("query").object().key("IMSI").value(IMSI).endObject();
            //key("query").object().key("IMSI").value(myIMSI).endObject();
            js.endObject();
            String registerJson = js.toString();
            logger.info("Sending IMSI in JSON = " + registerJson);
            HttpClient httpclient = new DefaultHttpClient();
            String key = "intellibitz";
            //EncryptionDecryption encryptDecrypt = new EncryptionDecryption();
            // String encrypted = encryptDecrypt.EncryptionDecryption(registerJson, key);
            ArrayList<NameValuePair> data = new ArrayList<NameValuePair>();
            data.add(new BasicNameValuePair("data_pack", registerJson));
            HttpPost httpPost = new HttpPost(getString(R.string.CatalogServer));
            httpPost.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
            HttpResponse resp = httpclient.execute(httpPost);
            String response = HttpUtils.getResponseString(resp);
            //logger.info("encrypted " + encrypted);
            //logger.info("decrypted " + decrypted);
            JSONObject jo = new JSONObject(response);
            strid = jo.getString("id");
            myDB.execSQL("INSERT INTO MobeegalUser (IMSI, UserID) VALUES ('" + IMSI + "','" + strid + "');");
        } else {
        }
        c.close();
    } catch (Exception e) {
    }
    act = (RadioButton) findViewById(R.id.activateradiobutton);
    //Service Activation
    if (act.isChecked() == true) {
        getService = "Activate";
        startService(new Intent("com.mobeegal.android.service.REMOTE_SERVICE"));
        myDB.execSQL("update serviceactivation set status='0' where service='deactivate';");
        Intent intent = new Intent(ServiceActivateDeactivate.this, TimeSettings.class);
        startActivityForResult(intent, 0);
        finish();
    } else //Service Deactivation
    {
        stopService(new Intent("com.mobeegal.android.service.REMOTE_SERVICE"));
        Intent intent = new Intent(ServiceActivateDeactivate.this, MstuffQuery.class);
        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.cancel(pi);
        /*
                    PostMethod httpPost =
                            new PostMethod(getString(R.string.RemoteServer));
                    httpPost.releaseConnection();
*/
        myDB.execSQL("update serviceactivation set status='1' where service='deactivate';");
        Intent intent1 = new Intent(ServiceActivateDeactivate.this, Settings.class);
        startActivityForResult(intent1, 0);
        finish();
    }
}
Example 95
Project: androidutils-master  File: MiscUtils.java View source code
/**
     *
     * @param context  context
     * @return  SerialNumber
     */
public static String getSerialNumber(Context context) {
    String serial = null;
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        serial = (String) get.invoke(c, "ro.serialno");
        if (serial == null || serial.trim().length() <= 0) {
            TelephonyManager tManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            serial = tManager.getDeviceId();
        }
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
    return serial;
}
Example 96
Project: android_packages_apps_Bluetooth-master  File: Config.java View source code
@SuppressWarnings("rawtypes")
private static synchronized boolean addAudioProfiles(String serviceName) {
    boolean isA2dpSinkEnabled = SystemProperties.getBoolean("persist.service.bt.a2dp.sink", false);
    boolean isHfpClientEnabled = SystemProperties.getBoolean("persist.service.bt.hfp.client", false);
    Log.d(TAG, "addA2dpProfile: isA2dpSinkEnabled = " + isA2dpSinkEnabled + "isHfpClientEnabled " + isHfpClientEnabled + " serviceName " + serviceName);
    /* If property not enabled and request is for A2DPSinkService, don't add */
    if ((serviceName.equals("A2dpSinkService")) && (!isA2dpSinkEnabled))
        return false;
    if ((serviceName.equals("A2dpService")) && (isA2dpSinkEnabled))
        return false;
    if ((serviceName.equals("HeadsetClientService")) && (!isHfpClientEnabled))
        return false;
    if ((serviceName.equals("HeadsetService")) && (isHfpClientEnabled))
        return false;
    return true;
}
Example 97
Project: appcan-android-master  File: PushReportUtility.java View source code
public static String getSerialNumber() {
    String serial = null;
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        serial = (String) get.invoke(c, "ro.serialno");
        System.out.println(serial);
    } catch (Exception ignored) {
    }
    return serial;
}
Example 98
Project: Exoplayer_VLC-master  File: HWDecoderUtil.java View source code
private static String getSystemProperty(String key, String def) {
    try {
        final ClassLoader cl = ClassLoader.getSystemClassLoader();
        final Class<?> SystemProperties = cl.loadClass("android.os.SystemProperties");
        final Class<?>[] paramTypes = new Class[] { String.class, String.class };
        final Method get = SystemProperties.getMethod("get", paramTypes);
        final Object[] params = new Object[] { key, def };
        return (String) get.invoke(SystemProperties, params);
    } catch (Exception e) {
        return def;
    }
}
Example 99
Project: frameworks_opt-master  File: DataCallResponse.java View source code
public SetupResult setLinkProperties(LinkProperties linkProperties, boolean okToUseSystemPropertyDns) {
    SetupResult result;
    // a failure we'll clear again at the bottom of this code.
    if (linkProperties == null)
        linkProperties = new LinkProperties();
    else
        linkProperties.clear();
    if (status == DcFailCause.NONE.getErrorCode()) {
        String propertyPrefix = "net." + ifname + ".";
        try {
            // set interface name
            linkProperties.setInterfaceName(ifname);
            // set link addresses
            if (addresses != null && addresses.length > 0) {
                for (String addr : addresses) {
                    addr = addr.trim();
                    if (addr.isEmpty())
                        continue;
                    LinkAddress la;
                    int addrPrefixLen;
                    String[] ap = addr.split("/");
                    if (ap.length == 2) {
                        addr = ap[0];
                        addrPrefixLen = Integer.parseInt(ap[1].replaceAll("[\\D]", ""));
                    } else {
                        addrPrefixLen = 0;
                    }
                    InetAddress ia;
                    try {
                        ia = NetworkUtils.numericToInetAddress(addr);
                    } catch (IllegalArgumentException e) {
                        throw new UnknownHostException("Non-numeric ip addr=" + addr);
                    }
                    if (!ia.isAnyLocalAddress()) {
                        if (addrPrefixLen == 0) {
                            // Assume point to point
                            addrPrefixLen = (ia instanceof Inet4Address) ? 32 : 128;
                        }
                        if (DBG)
                            Rlog.d(LOG_TAG, "addr/pl=" + addr + "/" + addrPrefixLen);
                        try {
                            la = new LinkAddress(ia, addrPrefixLen);
                        } catch (IllegalArgumentException e) {
                            throw new UnknownHostException("Bad parameter for LinkAddress, ia=" + ia.getHostAddress() + "/" + addrPrefixLen);
                        }
                        linkProperties.addLinkAddress(la);
                    }
                }
            } else {
                throw new UnknownHostException("no address for ifname=" + ifname);
            }
            // set dns servers
            if (dnses != null && dnses.length > 0) {
                for (String addr : dnses) {
                    addr = addr.trim();
                    if (addr.isEmpty())
                        continue;
                    InetAddress ia;
                    try {
                        ia = NetworkUtils.numericToInetAddress(addr);
                    } catch (IllegalArgumentException e) {
                        throw new UnknownHostException("Non-numeric dns addr=" + addr);
                    }
                    if (!ia.isAnyLocalAddress()) {
                        linkProperties.addDnsServer(ia);
                    }
                }
            } else if (okToUseSystemPropertyDns) {
                String dnsServers[] = new String[2];
                dnsServers[0] = SystemProperties.get(propertyPrefix + "dns1");
                dnsServers[1] = SystemProperties.get(propertyPrefix + "dns2");
                for (String dnsAddr : dnsServers) {
                    dnsAddr = dnsAddr.trim();
                    if (dnsAddr.isEmpty())
                        continue;
                    InetAddress ia;
                    try {
                        ia = NetworkUtils.numericToInetAddress(dnsAddr);
                    } catch (IllegalArgumentException e) {
                        throw new UnknownHostException("Non-numeric dns addr=" + dnsAddr);
                    }
                    if (!ia.isAnyLocalAddress()) {
                        linkProperties.addDnsServer(ia);
                    }
                }
            } else {
                throw new UnknownHostException("Empty dns response and no system default dns");
            }
            // set gateways
            if ((gateways == null) || (gateways.length == 0)) {
                String sysGateways = SystemProperties.get(propertyPrefix + "gw");
                if (sysGateways != null) {
                    gateways = sysGateways.split(" ");
                } else {
                    gateways = new String[0];
                }
            }
            for (String addr : gateways) {
                addr = addr.trim();
                if (addr.isEmpty())
                    continue;
                InetAddress ia;
                try {
                    ia = NetworkUtils.numericToInetAddress(addr);
                } catch (IllegalArgumentException e) {
                    throw new UnknownHostException("Non-numeric gateway addr=" + addr);
                }
                // Allow 0.0.0.0 or :: as a gateway; this indicates a point-to-point interface.
                linkProperties.addRoute(new RouteInfo(ia));
            }
            // set interface MTU
            // this may clobber the setting read from the APN db, but that's ok
            linkProperties.setMtu(mtu);
            result = SetupResult.SUCCESS;
        } catch (UnknownHostException e) {
            Rlog.d(LOG_TAG, "setLinkProperties: UnknownHostException " + e);
            e.printStackTrace();
            result = SetupResult.ERR_UnacceptableParameter;
        }
    } else {
        if (version < 4) {
            result = SetupResult.ERR_GetLastErrorFromRil;
        } else {
            result = SetupResult.ERR_RilError;
        }
    }
    // An error occurred so clear properties
    if (result != SetupResult.SUCCESS) {
        if (DBG) {
            Rlog.d(LOG_TAG, "setLinkProperties: error clearing LinkProperties " + "status=" + status + " result=" + result);
        }
        linkProperties.clear();
    }
    return result;
}
Example 100
Project: Lazy-master  File: MiscUtils.java View source code
/**
     *
     * @param context  context
     * @return  SerialNumber
     */
public static String getSerialNumber(Context context) {
    String serial = null;
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        serial = (String) get.invoke(c, "ro.serialno");
        if (serial == null || serial.trim().length() <= 0) {
            TelephonyManager tManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            serial = tManager.getDeviceId();
        }
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
    return serial;
}
Example 101
Project: OpenAtlasDemo-master  File: BundleLifecycleHandler.java View source code
private boolean isLewaOS() {
    try {
        return StringUtils.isNotEmpty((String) Class.forName("android.os.SystemProperties").getDeclaredMethod(ServicePermission.GET, new Class[] { String.class }).invoke(null, "ro.lewa.version"));
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}