/**
  * Retrieve a PendingIntent that will start a service, like calling {@link Context#startService
  * Context.startService()}. The start arguments given to the service will come from the extras of
  * the Intent.
  *
  * <p class="note">For security reasons, the {@link android.content.Intent} you supply here should
  * almost always be an <em>explicit intent</em>, that is specify an explicit component to be
  * delivered to through {@link Intent#setClass(android.content.Context, Class) Intent.setClass}
  *
  * @param context The Context in which this PendingIntent should start the service.
  * @param requestCode Private request code for the sender
  * @param intent An Intent describing the service to be started.
  * @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE}, {@link
  *     #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT}, or any of the flags as supported by
  *     {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts of the intent that
  *     can be supplied when the actual send happens.
  * @return Returns an existing or new PendingIntent matching the given parameters. May return null
  *     only if {@link #FLAG_NO_CREATE} has been supplied.
  */
 public static PendingIntent getService(
     Context context, int requestCode, @NonNull Intent intent, @Flags int flags) {
   String packageName = context.getPackageName();
   String resolvedType =
       intent != null ? intent.resolveTypeIfNeeded(context.getContentResolver()) : null;
   try {
     intent.prepareToLeaveProcess();
     IIntentSender target =
         ActivityManagerNative.getDefault()
             .getIntentSender(
                 ActivityManager.INTENT_SENDER_SERVICE,
                 packageName,
                 null,
                 null,
                 requestCode,
                 new Intent[] {intent},
                 resolvedType != null ? new String[] {resolvedType} : null,
                 flags,
                 null,
                 UserHandle.myUserId());
     return target != null ? new PendingIntent(target) : null;
   } catch (RemoteException e) {
   }
   return null;
 }
 /**
  * Like {@link #getActivity(Context, int, Intent, int)}, but allows an array of Intents to be
  * supplied. The last Intent in the array is taken as the primary key for the PendingIntent, like
  * the single Intent given to {@link #getActivity(Context, int, Intent, int)}. Upon sending the
  * resulting PendingIntent, all of the Intents are started in the same way as they would be by
  * passing them to {@link Context#startActivities(Intent[])}.
  *
  * <p class="note">The <em>first</em> intent in the array will be started outside of the context
  * of an existing activity, so you must use the {@link Intent#FLAG_ACTIVITY_NEW_TASK
  * Intent.FLAG_ACTIVITY_NEW_TASK} launch flag in the Intent. (Activities after the first in the
  * array are started in the context of the previous activity in the array, so
  * FLAG_ACTIVITY_NEW_TASK is not needed nor desired for them.)
  *
  * <p class="note">The <em>last</em> intent in the array represents the key for the PendingIntent.
  * In other words, it is the significant element for matching (as done with the single intent
  * given to {@link #getActivity(Context, int, Intent, int)}, its content will be the subject of
  * replacement by {@link #send(Context, int, Intent)} and {@link #FLAG_UPDATE_CURRENT}, etc. This
  * is because it is the most specific of the supplied intents, and the UI the user actually sees
  * when the intents are started.
  *
  * <p class="note">For security reasons, the {@link android.content.Intent} objects you supply
  * here should almost always be <em>explicit intents</em>, that is specify an explicit component
  * to be delivered to through {@link Intent#setClass(android.content.Context, Class)
  * Intent.setClass}
  *
  * @param context The Context in which this PendingIntent should start the activity.
  * @param requestCode Private request code for the sender
  * @param intents Array of Intents of the activities to be launched.
  * @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE}, {@link
  *     #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT}, or any of the flags as supported by
  *     {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts of the intent that
  *     can be supplied when the actual send happens.
  * @return Returns an existing or new PendingIntent matching the given parameters. May return null
  *     only if {@link #FLAG_NO_CREATE} has been supplied.
  */
 public static PendingIntent getActivities(
     Context context,
     int requestCode,
     @NonNull Intent[] intents,
     @Flags int flags,
     @Nullable Bundle options) {
   String packageName = context.getPackageName();
   String[] resolvedTypes = new String[intents.length];
   for (int i = 0; i < intents.length; i++) {
     intents[i].migrateExtraStreamToClipData();
     intents[i].prepareToLeaveProcess();
     resolvedTypes[i] = intents[i].resolveTypeIfNeeded(context.getContentResolver());
   }
   try {
     IIntentSender target =
         ActivityManagerNative.getDefault()
             .getIntentSender(
                 ActivityManager.INTENT_SENDER_ACTIVITY,
                 packageName,
                 null,
                 null,
                 requestCode,
                 intents,
                 resolvedTypes,
                 flags,
                 options,
                 UserHandle.myUserId());
     return target != null ? new PendingIntent(target) : null;
   } catch (RemoteException e) {
   }
   return null;
 }
 private RunningState(Context context) {
   mApplicationContext = context.getApplicationContext();
   mAm = (ActivityManager) mApplicationContext.getSystemService(Context.ACTIVITY_SERVICE);
   mPm = mApplicationContext.getPackageManager();
   mUm = (UserManager) mApplicationContext.getSystemService(Context.USER_SERVICE);
   mMyUserId = UserHandle.myUserId();
   mHideManagedProfiles = mMyUserId != UserHandle.USER_OWNER;
   mResumed = false;
   mBackgroundThread = new HandlerThread("RunningState:Background");
   mBackgroundThread.start();
   mBackgroundHandler = new BackgroundHandler(mBackgroundThread.getLooper());
   mUmBroadcastReceiver.register(mApplicationContext);
 }
 @Override
 public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) {
   // Override the fragment title for Wallpaper settings
   int titleRes = pref.getTitleRes();
   if (pref.getFragment().equals(WallpaperTypeSettings.class.getName())) {
     titleRes = R.string.wallpaper_settings_fragment_title;
   } else if (pref.getFragment().equals(OwnerInfoSettings.class.getName())
       && UserHandle.myUserId() != UserHandle.USER_OWNER) {
     titleRes = R.string.user_info_settings_title;
   }
   startPreferencePanel(pref.getFragment(), pref.getExtras(), titleRes, pref.getTitle(), null, 0);
   return true;
 }
 /**
  * Get an AccessibilityManager instance (create one if necessary).
  *
  * @param context Context in which this manager operates.
  * @hide
  */
 public static AccessibilityManager getInstance(Context context) {
   synchronized (sInstanceSync) {
     if (sInstance == null) {
       final int userId;
       if (Binder.getCallingUid() == Process.SYSTEM_UID
           || context.checkCallingOrSelfPermission(Manifest.permission.INTERACT_ACROSS_USERS)
               == PackageManager.PERMISSION_GRANTED
           || context.checkCallingOrSelfPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL)
               == PackageManager.PERMISSION_GRANTED) {
         userId = UserHandle.USER_CURRENT;
       } else {
         userId = UserHandle.myUserId();
       }
       sInstance = new AccessibilityManager(context, null, userId);
     }
   }
   return sInstance;
 }
 private CharSequence getDomainsSummary(String packageName) {
   // If the user has explicitly said "no" for this package, that's the
   // string we should show.
   int domainStatus = mPm.getIntentVerificationStatus(packageName, UserHandle.myUserId());
   if (domainStatus == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
     return mContext.getString(R.string.domain_urls_summary_none);
   }
   // Otherwise, ask package manager for the domains for this package,
   // and show the first one (or none if there aren't any).
   ArraySet<String> result = Utils.getHandledDomains(mPm, packageName);
   if (result.size() == 0) {
     return mContext.getString(R.string.domain_urls_summary_none);
   } else if (result.size() == 1) {
     return mContext.getString(R.string.domain_urls_summary_one, result.valueAt(0));
   } else {
     return mContext.getString(R.string.domain_urls_summary_some, result.valueAt(0));
   }
 }
  @Override
  public Set<X509Certificate> getCertificates() {
    // TODO: loading all of these is wasteful, we should instead use a keystore style API.
    synchronized (sLock) {
      if (sSystemCerts != null) {
        return sSystemCerts;
      }
      CertificateFactory certFactory;
      try {
        certFactory = CertificateFactory.getInstance("X.509");
      } catch (CertificateException e) {
        throw new RuntimeException("Failed to obtain X.509 CertificateFactory", e);
      }

      final String ANDROID_ROOT = System.getenv("ANDROID_ROOT");
      final File systemCaDir = new File(ANDROID_ROOT + "/etc/security/cacerts");
      final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
      final File userRemovedCaDir = new File(configDir, "cacerts-removed");
      // Sanity check
      if (!systemCaDir.isDirectory()) {
        throw new AssertionError(systemCaDir + " is not a directory");
      }

      Set<X509Certificate> systemCerts = new ArraySet<X509Certificate>();
      for (String caFile : systemCaDir.list()) {
        // Skip any CAs in the user's deleted directory.
        if (new File(userRemovedCaDir, caFile).exists()) {
          continue;
        }
        InputStream is = null;
        try {
          is = new BufferedInputStream(new FileInputStream(new File(systemCaDir, caFile)));
          systemCerts.add((X509Certificate) certFactory.generateCertificate(is));
        } catch (CertificateException | IOException e) {
          // Don't rethrow to be consistent with conscrypt's cert loading code.
          continue;
        } finally {
          IoUtils.closeQuietly(is);
        }
      }
      sSystemCerts = systemCerts;
      return sSystemCerts;
    }
  }
  @Override
  public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    if (preference.getKey().equals(KEY_FIRMWARE_VERSION)) {
      System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
      mHits[mHits.length - 1] = SystemClock.uptimeMillis();
      if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setClassName("android", com.android.internal.app.PlatLogoActivity.class.getName());
        try {
          startActivity(intent);
        } catch (Exception e) {
          Log.e(LOG_TAG, "Unable to start activity " + intent.toString());
        }
      }
    } else if (preference.getKey().equals(KEY_BUILD_NUMBER)) {
      // Don't enable developer options for secondary users.
      if (UserHandle.myUserId() != UserHandle.USER_OWNER) return true;

      if (mDevHitCountdown > 0) {
        mDevHitCountdown--;
        if (mDevHitCountdown == 0) {
          getActivity()
              .getSharedPreferences(DevelopmentSettings.PREF_FILE, Context.MODE_PRIVATE)
              .edit()
              .putBoolean(DevelopmentSettings.PREF_SHOW, true)
              .apply();
          if (mDevHitToast != null) {
            mDevHitToast.cancel();
          }
          mDevHitToast = Toast.makeText(getActivity(), R.string.show_dev_on, Toast.LENGTH_LONG);
          mDevHitToast.show();
        } else if (mDevHitCountdown > 0 && mDevHitCountdown < (TAPS_TO_BE_A_DEVELOPER - 2)) {
          if (mDevHitToast != null) {
            mDevHitToast.cancel();
          }
          mDevHitToast =
              Toast.makeText(
                  getActivity(),
                  getResources()
                      .getQuantityString(
                          R.plurals.show_dev_countdown, mDevHitCountdown, mDevHitCountdown),
                  Toast.LENGTH_SHORT);
          mDevHitToast.show();
        }
      } else if (mDevHitCountdown < 0) {
        if (mDevHitToast != null) {
          mDevHitToast.cancel();
        }
        mDevHitToast = Toast.makeText(getActivity(), R.string.show_dev_already, Toast.LENGTH_LONG);
        mDevHitToast.show();
      }
    } else if (preference.getKey().equals(KEY_MOD_VERSION)) {
      System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
      mHits[mHits.length - 1] = SystemClock.uptimeMillis();
      if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.putExtra("is_cid", true);
        intent.setClassName("android", com.android.internal.app.PlatLogoActivity.class.getName());
        try {
          startActivity(intent);
        } catch (Exception e) {
          Log.e(LOG_TAG, "Unable to start activity " + intent.toString());
        }
      }
    } else if (preference.getKey().equals(KEY_SELINUX_STATUS)) {
      System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
      mHits[mHits.length - 1] = SystemClock.uptimeMillis();
      if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
        if (SELinux.isSELinuxEnabled()) {
          if (!SELinux.isSELinuxEnforced()) {
            /* Display the warning dialog */
            AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
            alertDialog.setTitle(R.string.selinux_enable_title);
            alertDialog.setMessage(getResources().getString(R.string.selinux_enable_warning));
            alertDialog.setButton(
                DialogInterface.BUTTON_POSITIVE,
                getResources().getString(com.android.internal.R.string.ok),
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {
                    SELinux.setSELinuxEnforce(true);
                    String status = getResources().getString(R.string.selinux_status_enforcing);
                    setStringSummary(KEY_SELINUX_STATUS, status);
                  }
                });
            alertDialog.setButton(
                DialogInterface.BUTTON_NEGATIVE,
                getResources().getString(com.android.internal.R.string.cancel),
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {}
                });
            alertDialog.setOnCancelListener(
                new DialogInterface.OnCancelListener() {
                  public void onCancel(DialogInterface dialog) {}
                });
            alertDialog.show();

          } else {
            SELinux.setSELinuxEnforce(false);
          }
        }

        if (!SELinux.isSELinuxEnabled()) {
          String status = getResources().getString(R.string.selinux_status_disabled);
          setStringSummary(KEY_SELINUX_STATUS, status);
        } else if (!SELinux.isSELinuxEnforced()) {
          String status = getResources().getString(R.string.selinux_status_permissive);
          setStringSummary(KEY_SELINUX_STATUS, status);
        } else if (SELinux.isSELinuxEnforced()) {
          String status = getResources().getString(R.string.selinux_status_enforcing);
          setStringSummary(KEY_SELINUX_STATUS, status);
        }
      }
    }
    return super.onPreferenceTreeClick(preferenceScreen, preference);
  }
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    addPreferencesFromResource(R.xml.device_info_settings);

    setStringSummary(KEY_FIRMWARE_VERSION, Build.VERSION.RELEASE);
    findPreference(KEY_FIRMWARE_VERSION).setEnabled(true);
    setValueSummary(KEY_BASEBAND_VERSION, "gsm.version.baseband");
    setStringSummary(KEY_DEVICE_MODEL, Build.MODEL + getMsvSuffix());
    setValueSummary(KEY_EQUIPMENT_ID, PROPERTY_EQUIPMENT_ID);
    setStringSummary(KEY_DEVICE_MODEL, Build.MODEL);
    setStringSummary(KEY_BUILD_NUMBER, Build.DISPLAY);
    findPreference(KEY_BUILD_NUMBER).setEnabled(true);
    findPreference(KEY_KERNEL_VERSION).setSummary(getFormattedKernelVersion());
    setValueSummary(KEY_MOD_VERSION, "ro.cm.version");
    findPreference(KEY_MOD_VERSION).setEnabled(true);
    setValueSummary(KEY_MOD_BUILD_DATE, "ro.build.date");

    if (!SELinux.isSELinuxEnabled()) {
      String status = getResources().getString(R.string.selinux_status_disabled);
      setStringSummary(KEY_SELINUX_STATUS, status);
    } else if (!SELinux.isSELinuxEnforced()) {
      String status = getResources().getString(R.string.selinux_status_permissive);
      setStringSummary(KEY_SELINUX_STATUS, status);
    }
    findPreference(KEY_SELINUX_STATUS).setEnabled(true);

    if (MSimTelephonyManager.getDefault().isMultiSimEnabled()) {
      findPreference(KEY_STATUS)
          .getIntent()
          .setClassName("com.android.settings", "com.android.settings.deviceinfo.msim.MSimStatus");
    }

    // Remove selinux information if property is not present
    removePreferenceIfPropertyMissing(
        getPreferenceScreen(), KEY_SELINUX_STATUS, PROPERTY_SELINUX_STATUS);

    String cpuInfo = getCPUInfo();
    String memInfo = getMemInfo();

    // Only the owner should see the Updater settings, if it exists
    if (UserHandle.myUserId() == UserHandle.USER_OWNER) {
      removePreferenceIfPackageNotInstalled(findPreference(KEY_CM_UPDATES));
    } else {
      getPreferenceScreen().removePreference(findPreference(KEY_CM_UPDATES));
    }

    if (cpuInfo != null) {
      setStringSummary(KEY_DEVICE_CPU, cpuInfo);
    } else {
      getPreferenceScreen().removePreference(findPreference(KEY_DEVICE_CPU));
    }

    if (memInfo != null) {
      setStringSummary(KEY_DEVICE_MEMORY, memInfo);
    } else {
      getPreferenceScreen().removePreference(findPreference(KEY_DEVICE_MEMORY));
    }

    // Remove Safety information preference if PROPERTY_URL_SAFETYLEGAL is not set
    removePreferenceIfPropertyMissing(
        getPreferenceScreen(), "safetylegal", PROPERTY_URL_SAFETYLEGAL);

    // Remove Equipment id preference if FCC ID is not set by RIL
    removePreferenceIfPropertyMissing(
        getPreferenceScreen(), KEY_EQUIPMENT_ID, PROPERTY_EQUIPMENT_ID);

    // Remove Baseband version if wifi-only device
    if (Utils.isWifiOnly(getActivity())
        || (MSimTelephonyManager.getDefault().isMultiSimEnabled())) {
      getPreferenceScreen().removePreference(findPreference(KEY_BASEBAND_VERSION));
    }

    /*
     * Settings is a generic app and should not contain any device-specific
     * info.
     */
    final Activity act = getActivity();
    // These are contained in the "container" preference group
    PreferenceGroup parentPreference = (PreferenceGroup) findPreference(KEY_CONTAINER);
    Utils.updatePreferenceToSpecificActivityOrRemove(
        act,
        parentPreference,
        KEY_TERMS,
        Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
    Utils.updatePreferenceToSpecificActivityOrRemove(
        act,
        parentPreference,
        KEY_LICENSE,
        Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
    Utils.updatePreferenceToSpecificActivityOrRemove(
        act,
        parentPreference,
        KEY_COPYRIGHT,
        Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
    Utils.updatePreferenceToSpecificActivityOrRemove(
        act,
        parentPreference,
        KEY_TEAM,
        Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);

    // These are contained by the root preference screen
    parentPreference = getPreferenceScreen();
    if (UserHandle.myUserId() == UserHandle.USER_OWNER) {
      Utils.updatePreferenceToSpecificActivityOrRemove(
          act,
          parentPreference,
          KEY_SYSTEM_UPDATE_SETTINGS,
          Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
      /* Make sure the activity is provided by who we want... */
      if (findPreference(KEY_SYSTEM_UPDATE_SETTINGS) != null)
        removePreferenceIfPackageNotInstalled(findPreference(KEY_SYSTEM_UPDATE_SETTINGS));
    } else {
      // Remove for secondary users
      removePreference(KEY_SYSTEM_UPDATE_SETTINGS);
    }
    Utils.updatePreferenceToSpecificActivityOrRemove(
        act,
        parentPreference,
        KEY_CONTRIBUTORS,
        Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);

    // Read platform settings for additional system update setting
    removePreferenceIfBoolFalse(
        KEY_UPDATE_SETTING, R.bool.config_additional_system_update_setting_enable);

    // Remove regulatory information if not enabled.
    removePreferenceIfBoolFalse(KEY_REGULATORY_INFO, R.bool.config_show_regulatory_info);
  }
Example #10
0
 /**
  * Checks whether this screen will have anything to show on this device. This is called by the
  * shortcut picker for Settings shortcuts (home screen widget).
  *
  * @param context a context object for getting a system service.
  * @return whether Tether & portable hotspot should be shown in the shortcuts picker.
  */
 public static boolean showInShortcuts(Context context) {
   final ConnectivityManager cm =
       (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
   final boolean isSecondaryUser = UserHandle.myUserId() != UserHandle.USER_OWNER;
   return !isSecondaryUser && cm.isTetheringSupported();
 }
Example #11
0
 @Override
 public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
   if (preference.getKey().equals(KEY_FIRMWARE_VERSION)) {
     System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
     mHits[mHits.length - 1] = SystemClock.uptimeMillis();
     if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
       Intent intent = new Intent(Intent.ACTION_MAIN);
       intent.setClassName("android", com.android.internal.app.PlatLogoActivity.class.getName());
       try {
         startActivity(intent);
       } catch (Exception e) {
         Log.e(LOG_TAG, "Unable to start activity " + intent.toString());
       }
     }
   } else if (preference.getKey().equals(KEY_BUILD_NUMBER)) {
     // Only allow the owner of the device to turn on dev and performance options
     if (UserHandle.myUserId() == UserHandle.USER_OWNER) {
       if (mDevHitCountdown > 0) {
         mDevHitCountdown--;
         if (mDevHitCountdown == 0) {
           getActivity()
               .getSharedPreferences(DevelopmentSettings.PREF_FILE, Context.MODE_PRIVATE)
               .edit()
               .putBoolean(DevelopmentSettings.PREF_SHOW, true)
               .apply();
           if (mDevHitToast != null) {
             mDevHitToast.cancel();
           }
           mDevHitToast = Toast.makeText(getActivity(), R.string.show_dev_on, Toast.LENGTH_LONG);
           mDevHitToast.show();
         } else if (mDevHitCountdown > 0 && mDevHitCountdown < (TAPS_TO_BE_A_DEVELOPER - 2)) {
           if (mDevHitToast != null) {
             mDevHitToast.cancel();
           }
           mDevHitToast =
               Toast.makeText(
                   getActivity(),
                   getResources()
                       .getQuantityString(
                           R.plurals.show_dev_countdown, mDevHitCountdown, mDevHitCountdown),
                   Toast.LENGTH_SHORT);
           mDevHitToast.show();
         }
       } else if (mDevHitCountdown < 0) {
         if (mDevHitToast != null) {
           mDevHitToast.cancel();
         }
         mDevHitToast =
             Toast.makeText(getActivity(), R.string.show_dev_already, Toast.LENGTH_LONG);
         mDevHitToast.show();
       }
     }
   } else if (preference.getKey().equals(KEY_MOD_VERSION)) {
     System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
     mHits[mHits.length - 1] = SystemClock.uptimeMillis();
     if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {
       Intent intent = new Intent(Intent.ACTION_MAIN);
       intent.putExtra("is_cid", true);
       intent.setClassName("android", com.android.internal.app.PlatLogoActivity.class.getName());
       try {
         startActivity(intent);
       } catch (Exception e) {
         Log.e(LOG_TAG, "Unable to start activity " + intent.toString());
       }
     }
   }
   return super.onPreferenceTreeClick(preferenceScreen, preference);
 }
 public RunningProcessesView(Context context, AttributeSet attrs) {
   super(context, attrs);
   mMyUserId = UserHandle.myUserId();
 }
  private void updateServicesPreferences() {
    // Since services category is auto generated we have to do a pass
    // to generate it since services can come and go and then based on
    // the global accessibility state to decided whether it is enabled.

    // Generate.
    mServicesCategory.removeAll();

    AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(getActivity());

    List<AccessibilityServiceInfo> installedServices =
        accessibilityManager.getInstalledAccessibilityServiceList();
    Set<ComponentName> enabledServices =
        AccessibilityUtils.getEnabledServicesFromSettings(getActivity());
    List<String> permittedServices = mDpm.getPermittedAccessibilityServices(UserHandle.myUserId());
    final boolean accessibilityEnabled =
        Settings.Secure.getInt(getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, 0) == 1;

    for (int i = 0, count = installedServices.size(); i < count; ++i) {
      AccessibilityServiceInfo info = installedServices.get(i);

      PreferenceScreen preference = getPreferenceManager().createPreferenceScreen(getActivity());
      String title = info.getResolveInfo().loadLabel(getPackageManager()).toString();

      ServiceInfo serviceInfo = info.getResolveInfo().serviceInfo;
      ComponentName componentName = new ComponentName(serviceInfo.packageName, serviceInfo.name);

      preference.setKey(componentName.flattenToString());

      preference.setTitle(title);
      final boolean serviceEnabled =
          accessibilityEnabled && enabledServices.contains(componentName);
      String serviceEnabledString;
      if (serviceEnabled) {
        serviceEnabledString = getString(R.string.accessibility_feature_state_on);
      } else {
        serviceEnabledString = getString(R.string.accessibility_feature_state_off);
      }

      // Disable all accessibility services that are not permitted.
      String packageName = serviceInfo.packageName;
      boolean serviceAllowed = permittedServices == null || permittedServices.contains(packageName);
      preference.setEnabled(serviceAllowed || serviceEnabled);

      String summaryString;
      if (serviceAllowed) {
        summaryString = serviceEnabledString;
      } else {
        summaryString = getString(R.string.accessibility_feature_or_input_method_not_allowed);
      }
      preference.setSummary(summaryString);

      preference.setOrder(i);
      preference.setFragment(ToggleAccessibilityServicePreferenceFragment.class.getName());
      preference.setPersistent(true);

      Bundle extras = preference.getExtras();
      extras.putString(EXTRA_PREFERENCE_KEY, preference.getKey());
      extras.putBoolean(EXTRA_CHECKED, serviceEnabled);
      extras.putString(EXTRA_TITLE, title);

      String description = info.loadDescription(getPackageManager());
      if (TextUtils.isEmpty(description)) {
        description = getString(R.string.accessibility_service_default_description);
      }
      extras.putString(EXTRA_SUMMARY, description);

      String settingsClassName = info.getSettingsActivityName();
      if (!TextUtils.isEmpty(settingsClassName)) {
        extras.putString(
            EXTRA_SETTINGS_TITLE, getString(R.string.accessibility_menu_item_settings));
        extras.putString(
            EXTRA_SETTINGS_COMPONENT_NAME,
            new ComponentName(info.getResolveInfo().serviceInfo.packageName, settingsClassName)
                .flattenToString());
      }

      extras.putParcelable(EXTRA_COMPONENT_NAME, componentName);

      mServicesCategory.addPreference(preference);
    }

    if (mServicesCategory.getPreferenceCount() == 0) {
      if (mNoServicesMessagePreference == null) {
        mNoServicesMessagePreference = new Preference(getActivity());
        mNoServicesMessagePreference.setPersistent(false);
        mNoServicesMessagePreference.setLayoutResource(R.layout.text_description_preference);
        mNoServicesMessagePreference.setSelectable(false);
        mNoServicesMessagePreference.setSummary(
            getString(R.string.accessibility_no_services_installed));
      }
      mServicesCategory.addPreference(mNoServicesMessagePreference);
    }
  }
 /**
  * Returns a String pattern that can be used to format the time according to the current locale
  * and the user's 12-/24-hour clock preference.
  *
  * @param context the application context
  * @hide
  */
 public static String getTimeFormatString(Context context) {
   return getTimeFormatString(context, UserHandle.myUserId());
 }
Example #15
0
 private void initPhoneInstance() {
   if (UserHandle.myUserId() == UserHandle.USER_OWNER && mUtility.isValidSubId()) {
     mPhone = PhoneFactory.getPhone(mUtility.getSlotId());
     initPhoneStateListener();
   }
 }
  private void updateVolumesLocked() {
    mRoots.clear();

    final int userId = UserHandle.myUserId();
    final List<VolumeInfo> volumes = mStorageManager.getVolumes();
    for (VolumeInfo volume : volumes) {
      if (!volume.isMountedReadable()) continue;

      final String rootId;
      final String title;
      if (volume.getType() == VolumeInfo.TYPE_EMULATED) {
        // We currently only support a single emulated volume mounted at
        // a time, and it's always considered the primary
        rootId = ROOT_ID_PRIMARY_EMULATED;
        if (VolumeInfo.ID_EMULATED_INTERNAL.equals(volume.getId())) {
          title = getContext().getString(R.string.root_internal_storage);
        } else {
          final VolumeInfo privateVol = mStorageManager.findPrivateForEmulated(volume);
          title = mStorageManager.getBestVolumeDescription(privateVol);
        }
      } else if (volume.getType() == VolumeInfo.TYPE_PUBLIC) {
        rootId = volume.getFsUuid();
        title = mStorageManager.getBestVolumeDescription(volume);
      } else {
        // Unsupported volume; ignore
        continue;
      }

      if (TextUtils.isEmpty(rootId)) {
        Log.d(TAG, "Missing UUID for " + volume.getId() + "; skipping");
        continue;
      }
      if (mRoots.containsKey(rootId)) {
        Log.w(TAG, "Duplicate UUID " + rootId + " for " + volume.getId() + "; skipping");
        continue;
      }

      try {
        final RootInfo root = new RootInfo();
        mRoots.put(rootId, root);

        root.rootId = rootId;
        root.flags =
            Root.FLAG_SUPPORTS_CREATE
                | Root.FLAG_LOCAL_ONLY
                | Root.FLAG_ADVANCED
                | Root.FLAG_SUPPORTS_SEARCH
                | Root.FLAG_SUPPORTS_IS_CHILD;
        root.title = title;
        if (volume.getType() == VolumeInfo.TYPE_PUBLIC) {
          root.flags |= Root.FLAG_HAS_SETTINGS;
        }
        if (volume.isVisibleForRead(userId)) {
          root.visiblePath = volume.getPathForUser(userId);
        } else {
          root.visiblePath = null;
        }
        root.path = volume.getInternalPathForUser(userId);
        root.docId = getDocIdForFile(root.path);

      } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
      }
    }

    Log.d(TAG, "After updating volumes, found " + mRoots.size() + " active roots");

    // Note this affects content://com.android.externalstorage.documents/root/39BD-07C5
    // as well as content://com.android.externalstorage.documents/document/*/children,
    // so just notify on content://com.android.externalstorage.documents/.
    getContext().getContentResolver().notifyChange(BASE_URI, null, false);
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
      mManageMobilePlanMessage = savedInstanceState.getString(SAVED_MANAGE_MOBILE_PLAN_MSG);
    }
    log("onCreate: mManageMobilePlanMessage=" + mManageMobilePlanMessage);

    mCm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    mTm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    mPm = getPackageManager();
    mUm = (UserManager) getSystemService(Context.USER_SERVICE);

    addPreferencesFromResource(R.xml.wireless_settings);

    final int myUserId = UserHandle.myUserId();
    final boolean isSecondaryUser = myUserId != UserHandle.USER_OWNER;

    final Activity activity = getActivity();
    mAirplaneModePreference = (SwitchPreference) findPreference(KEY_TOGGLE_AIRPLANE);
    SwitchPreference nfc = (SwitchPreference) findPreference(KEY_TOGGLE_NFC);
    PreferenceScreen androidBeam = (PreferenceScreen) findPreference(KEY_ANDROID_BEAM_SETTINGS);
    SwitchPreference nsd = (SwitchPreference) findPreference(KEY_TOGGLE_NSD);

    mAirplaneModeEnabler = new AirplaneModeEnabler(activity, mAirplaneModePreference);
    mNfcEnabler = new NfcEnabler(activity, nfc, androidBeam);

    mButtonWfc = (PreferenceScreen) findPreference(KEY_WFC_SETTINGS);

    // Remove NSD checkbox by default
    getPreferenceScreen().removePreference(nsd);
    // mNsdEnabler = new NsdEnabler(activity, nsd);

    String toggleable =
        Settings.Global.getString(
            activity.getContentResolver(), Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);

    // enable/disable wimax depending on the value in config.xml
    final boolean isWimaxEnabled =
        !isSecondaryUser
            && this.getResources().getBoolean(com.android.internal.R.bool.config_wimaxEnabled);
    if (!isWimaxEnabled || mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
      PreferenceScreen root = getPreferenceScreen();
      Preference ps = (Preference) findPreference(KEY_WIMAX_SETTINGS);
      if (ps != null) root.removePreference(ps);
    } else {
      if (toggleable == null
          || !toggleable.contains(Settings.Global.RADIO_WIMAX) && isWimaxEnabled) {
        Preference ps = (Preference) findPreference(KEY_WIMAX_SETTINGS);
        ps.setDependency(KEY_TOGGLE_AIRPLANE);
      }
    }

    // Manually set dependencies for Wifi when not toggleable.
    if (toggleable == null || !toggleable.contains(Settings.Global.RADIO_WIFI)) {
      findPreference(KEY_VPN_SETTINGS).setDependency(KEY_TOGGLE_AIRPLANE);
    }
    // Disable VPN.
    if (isSecondaryUser || mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
      removePreference(KEY_VPN_SETTINGS);
    }

    // Manually set dependencies for Bluetooth when not toggleable.
    if (toggleable == null || !toggleable.contains(Settings.Global.RADIO_BLUETOOTH)) {
      // No bluetooth-dependent items in the list. Code kept in case one is added later.
    }

    // Manually set dependencies for NFC when not toggleable.
    if (toggleable == null || !toggleable.contains(Settings.Global.RADIO_NFC)) {
      findPreference(KEY_TOGGLE_NFC).setDependency(KEY_TOGGLE_AIRPLANE);
      findPreference(KEY_ANDROID_BEAM_SETTINGS).setDependency(KEY_TOGGLE_AIRPLANE);
    }

    // Remove NFC if not available
    mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);
    if (mNfcAdapter == null) {
      getPreferenceScreen().removePreference(nfc);
      getPreferenceScreen().removePreference(androidBeam);
      mNfcEnabler = null;
    }

    // Remove Mobile Network Settings and Manage Mobile Plan for secondary users,
    // if it's a wifi-only device, or if the settings are restricted.
    if (isSecondaryUser
        || Utils.isWifiOnly(getActivity())
        || mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
      removePreference(KEY_MOBILE_NETWORK_SETTINGS);
      removePreference(KEY_MANAGE_MOBILE_PLAN);
    }
    // Remove Mobile Network Settings and Manage Mobile Plan
    // if config_show_mobile_plan sets false.
    final boolean isMobilePlanEnabled =
        this.getResources().getBoolean(R.bool.config_show_mobile_plan);
    if (!isMobilePlanEnabled) {
      Preference pref = findPreference(KEY_MANAGE_MOBILE_PLAN);
      if (pref != null) {
        removePreference(KEY_MANAGE_MOBILE_PLAN);
      }
    }

    // Remove Airplane Mode settings if it's a stationary device such as a TV.
    if (mPm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)) {
      removePreference(KEY_TOGGLE_AIRPLANE);
    }

    // Enable Proxy selector settings if allowed.
    Preference mGlobalProxy = findPreference(KEY_PROXY_SETTINGS);
    final DevicePolicyManager mDPM =
        (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
    // proxy UI disabled until we have better app support
    getPreferenceScreen().removePreference(mGlobalProxy);
    mGlobalProxy.setEnabled(mDPM.getGlobalProxyAdmin() == null);

    // Disable Tethering if it's not allowed or if it's a wifi-only device
    final ConnectivityManager cm =
        (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (isSecondaryUser
        || !cm.isTetheringSupported()
        || mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
      getPreferenceScreen().removePreference(findPreference(KEY_TETHER_SETTINGS));
    } else {
      Preference p = findPreference(KEY_TETHER_SETTINGS);
      p.setTitle(com.android.settingslib.Utils.getTetheringLabel(cm));

      // Grey out if provisioning is not available.
      p.setEnabled(!TetherSettings.isProvisioningNeededButUnavailable(getActivity()));
    }

    // Enable link to CMAS app settings depending on the value in config.xml.
    boolean isCellBroadcastAppLinkEnabled =
        this.getResources().getBoolean(com.android.internal.R.bool.config_cellBroadcastAppLinks);
    try {
      if (isCellBroadcastAppLinkEnabled) {
        if (mPm.getApplicationEnabledSetting("com.android.cellbroadcastreceiver")
            == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
          isCellBroadcastAppLinkEnabled = false; // CMAS app disabled
        }
      }
    } catch (IllegalArgumentException ignored) {
      isCellBroadcastAppLinkEnabled = false; // CMAS app not installed
    }
    if (isSecondaryUser
        || !isCellBroadcastAppLinkEnabled
        || mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS)) {
      PreferenceScreen root = getPreferenceScreen();
      Preference ps = findPreference(KEY_CELL_BROADCAST_SETTINGS);
      if (ps != null) root.removePreference(ps);
    }
  }
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    addPreferencesFromResource(R.xml.device_info_settings);

    setStringSummary(KEY_FIRMWARE_VERSION, Build.VERSION.RELEASE);
    findPreference(KEY_FIRMWARE_VERSION).setEnabled(true);
    setValueSummary(KEY_BASEBAND_VERSION, "gsm.version.baseband");
    setStringSummary(KEY_DEVICE_MODEL, Build.MODEL + getMsvSuffix());
    setValueSummary(KEY_EQUIPMENT_ID, PROPERTY_EQUIPMENT_ID);
    setStringSummary(KEY_DEVICE_MODEL, Build.MODEL);
    setStringSummary(KEY_BUILD_NUMBER, Build.DISPLAY);
    findPreference(KEY_BUILD_NUMBER).setEnabled(true);
    findPreference(KEY_KERNEL_VERSION).setSummary(getFormattedKernelVersion());
    setValueSummary(KEY_MOD_VERSION, "ro.aokp.version");
    findPreference(KEY_MOD_VERSION).setEnabled(true);

    if (!SELinux.isSELinuxEnabled()) {
      String status = getResources().getString(R.string.selinux_status_disabled);
      setStringSummary(KEY_SELINUX_STATUS, status);
    } else if (!SELinux.isSELinuxEnforced()) {
      String status = getResources().getString(R.string.selinux_status_permissive);
      setStringSummary(KEY_SELINUX_STATUS, status);
    }

    // Remove selinux information if property is not present
    removePreferenceIfPropertyMissing(
        getPreferenceScreen(), KEY_SELINUX_STATUS, PROPERTY_SELINUX_STATUS);

    addStringPreference(KEY_DEVICE_CHIPSET, SystemProperties.get("ro.device.chipset", null));
    addStringPreference(KEY_DEVICE_CPU, SystemProperties.get("ro.device.cpu", getCPUInfo()));
    addStringPreference(KEY_DEVICE_GPU, SystemProperties.get("ro.device.gpu", null));
    addStringPreference(KEY_DEVICE_MEMORY, getMemInfo());
    addStringPreference(KEY_DEVICE_FRONT_CAMERA, SystemProperties.get("ro.device.front_cam", null));
    addStringPreference(KEY_DEVICE_REAR_CAMERA, SystemProperties.get("ro.device.rear_cam", null));
    addStringPreference(
        KEY_DEVICE_SCREEN_RESOLUTION, SystemProperties.get("ro.device.screen_res", null));

    // Remove Safety information preference if PROPERTY_URL_SAFETYLEGAL is not set
    removePreferenceIfPropertyMissing(
        getPreferenceScreen(), "safetylegal", PROPERTY_URL_SAFETYLEGAL);

    // Remove Equipment id preference if FCC ID is not set by RIL
    removePreferenceIfPropertyMissing(
        getPreferenceScreen(), KEY_EQUIPMENT_ID, PROPERTY_EQUIPMENT_ID);

    // Remove Baseband version if wifi-only device
    if (Utils.isWifiOnly(getActivity())) {
      getPreferenceScreen().removePreference(findPreference(KEY_BASEBAND_VERSION));
    }

    /*
     * Settings is a generic app and should not contain any device-specific
     * info.
     */
    final Activity act = getActivity();
    // These are contained in the "container" preference group
    PreferenceGroup parentPreference = (PreferenceGroup) findPreference(KEY_CONTAINER);
    Utils.updatePreferenceToSpecificActivityOrRemove(
        act,
        parentPreference,
        KEY_TERMS,
        Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
    Utils.updatePreferenceToSpecificActivityOrRemove(
        act,
        parentPreference,
        KEY_LICENSE,
        Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
    Utils.updatePreferenceToSpecificActivityOrRemove(
        act,
        parentPreference,
        KEY_COPYRIGHT,
        Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
    Utils.updatePreferenceToSpecificActivityOrRemove(
        act,
        parentPreference,
        KEY_TEAM,
        Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);

    // These are contained by the root preference screen
    parentPreference = getPreferenceScreen();
    if (UserHandle.myUserId() == UserHandle.USER_OWNER) {
      Utils.updatePreferenceToSpecificActivityOrRemove(
          act,
          parentPreference,
          KEY_SYSTEM_UPDATE_SETTINGS,
          Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
    } else {
      // Remove for secondary users
      removePreference(KEY_SYSTEM_UPDATE_SETTINGS);
    }
    Utils.updatePreferenceToSpecificActivityOrRemove(
        act,
        parentPreference,
        KEY_CONTRIBUTORS,
        Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);

    // Read platform settings for additional system update setting
    removePreferenceIfBoolFalse(
        KEY_UPDATE_SETTING, R.bool.config_additional_system_update_setting_enable);

    // Remove regulatory information if not enabled.
    removePreferenceIfBoolFalse(KEY_REGULATORY_INFO, R.bool.config_show_regulatory_info);
  }
        @Override
        public List<String> getNonIndexableKeys(Context context) {
          final ArrayList<String> result = new ArrayList<String>();

          result.add(KEY_TOGGLE_NSD);

          final UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
          final int myUserId = UserHandle.myUserId();
          final boolean isSecondaryUser = myUserId != UserHandle.USER_OWNER;
          final boolean isWimaxEnabled =
              !isSecondaryUser
                  && context
                      .getResources()
                      .getBoolean(com.android.internal.R.bool.config_wimaxEnabled);
          if (!isWimaxEnabled
              || um.hasUserRestriction(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
            result.add(KEY_WIMAX_SETTINGS);
          }

          if (isSecondaryUser) { // Disable VPN
            result.add(KEY_VPN_SETTINGS);
          }

          // Remove NFC if not available
          final NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
          if (manager != null) {
            NfcAdapter adapter = manager.getDefaultAdapter();
            if (adapter == null) {
              result.add(KEY_TOGGLE_NFC);
              result.add(KEY_ANDROID_BEAM_SETTINGS);
            }
          }

          // Remove Mobile Network Settings and Manage Mobile Plan if it's a wifi-only device.
          if (isSecondaryUser || Utils.isWifiOnly(context)) {
            result.add(KEY_MOBILE_NETWORK_SETTINGS);
            result.add(KEY_MANAGE_MOBILE_PLAN);
          }

          // Remove Mobile Network Settings and Manage Mobile Plan
          // if config_show_mobile_plan sets false.
          final boolean isMobilePlanEnabled =
              context.getResources().getBoolean(R.bool.config_show_mobile_plan);
          if (!isMobilePlanEnabled) {
            result.add(KEY_MANAGE_MOBILE_PLAN);
          }

          final PackageManager pm = context.getPackageManager();

          // Remove Airplane Mode settings if it's a stationary device such as a TV.
          if (pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)) {
            result.add(KEY_TOGGLE_AIRPLANE);
          }

          // proxy UI disabled until we have better app support
          result.add(KEY_PROXY_SETTINGS);

          // Disable Tethering if it's not allowed or if it's a wifi-only device
          ConnectivityManager cm =
              (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (isSecondaryUser || !cm.isTetheringSupported()) {
            result.add(KEY_TETHER_SETTINGS);
          }

          // Enable link to CMAS app settings depending on the value in config.xml.
          boolean isCellBroadcastAppLinkEnabled =
              context
                  .getResources()
                  .getBoolean(com.android.internal.R.bool.config_cellBroadcastAppLinks);
          try {
            if (isCellBroadcastAppLinkEnabled) {
              if (pm.getApplicationEnabledSetting("com.android.cellbroadcastreceiver")
                  == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                isCellBroadcastAppLinkEnabled = false; // CMAS app disabled
              }
            }
          } catch (IllegalArgumentException ignored) {
            isCellBroadcastAppLinkEnabled = false; // CMAS app not installed
          }
          if (isSecondaryUser || !isCellBroadcastAppLinkEnabled) {
            result.add(KEY_CELL_BROADCAST_SETTINGS);
          }

          return result;
        }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final Activity activity = getActivity();
    final ContentResolver resolver = activity.getContentResolver();
    mHardware = CMHardwareManager.getInstance(activity);
    addPreferencesFromResource(R.xml.display_settings);

    PreferenceCategory displayPrefs = (PreferenceCategory) findPreference(KEY_CATEGORY_DISPLAY);

    mDisplayRotationPreference = (PreferenceScreen) findPreference(KEY_DISPLAY_ROTATION);

    mScreenSaverPreference = findPreference(KEY_SCREEN_SAVER);
    if (mScreenSaverPreference != null
        && getResources().getBoolean(com.android.internal.R.bool.config_dreamsSupported) == false) {
      getPreferenceScreen().removePreference(mScreenSaverPreference);
    }

    mScreenTimeoutPreference = (ListPreference) findPreference(KEY_SCREEN_TIMEOUT);
    final long currentTimeout =
        Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT, FALLBACK_SCREEN_TIMEOUT_VALUE);
    mScreenTimeoutPreference.setValue(String.valueOf(currentTimeout));
    mScreenTimeoutPreference.setOnPreferenceChangeListener(this);
    disableUnusableTimeouts(mScreenTimeoutPreference);
    updateTimeoutPreferenceDescription(currentTimeout);
    updateDisplayRotationPreferenceDescription();

    mLcdDensityPreference = (ListPreference) findPreference(KEY_LCD_DENSITY);
    if (mLcdDensityPreference != null) {
      if (UserHandle.myUserId() != UserHandle.USER_OWNER) {
        displayPrefs.removePreference(mLcdDensityPreference);
      } else {
        int defaultDensity = getDefaultDensity();
        int currentDensity = getCurrentDensity();
        if (currentDensity < 10 || currentDensity >= 1000) {
          // Unsupported value, force default
          currentDensity = defaultDensity;
        }

        int factor = defaultDensity >= 480 ? 40 : 20;
        int minimumDensity = defaultDensity - 4 * factor;
        int currentIndex = -1;
        String[] densityEntries = new String[7];
        String[] densityValues = new String[7];
        for (int idx = 0; idx < 7; ++idx) {
          int val = minimumDensity + factor * idx;
          int valueFormatResId =
              val == defaultDensity
                  ? R.string.lcd_density_default_value_format
                  : R.string.lcd_density_value_format;

          densityEntries[idx] = getString(valueFormatResId, val);
          densityValues[idx] = Integer.toString(val);
          if (currentDensity == val) {
            currentIndex = idx;
          }
        }
        mLcdDensityPreference.setEntries(densityEntries);
        mLcdDensityPreference.setEntryValues(densityValues);
        if (currentIndex != -1) {
          mLcdDensityPreference.setValueIndex(currentIndex);
        }
        mLcdDensityPreference.setOnPreferenceChangeListener(this);
        updateLcdDensityPreferenceDescription(currentDensity);
      }
    }

    mFontSizePref = (FontDialogPreference) findPreference(KEY_FONT_SIZE);
    mFontSizePref.setOnPreferenceChangeListener(this);
    mFontSizePref.setOnPreferenceClickListener(this);

    if (isAutomaticBrightnessAvailable(getResources())) {
      mAutoBrightnessPreference = (SwitchPreference) findPreference(KEY_AUTO_BRIGHTNESS);
      mAutoBrightnessPreference.setOnPreferenceChangeListener(this);
    } else {
      removePreference(KEY_AUTO_BRIGHTNESS);
    }

    if (isLiftToWakeAvailable(activity)) {
      mLiftToWakePreference = (SwitchPreference) findPreference(KEY_LIFT_TO_WAKE);
      mLiftToWakePreference.setOnPreferenceChangeListener(this);
    } else {
      removePreference(KEY_LIFT_TO_WAKE);
    }

    PreferenceCategory advancedPrefs = (PreferenceCategory) findPreference(CATEGORY_ADVANCED);

    mDozeFragement = (PreferenceScreen) findPreference(KEY_DOZE_FRAGMENT);
    if (!Utils.isDozeAvailable(activity)) {
      getPreferenceScreen().removePreference(mDozeFragement);
      mDozeFragement = null;
    }

    mTapToWake = (SwitchPreference) findPreference(KEY_TAP_TO_WAKE);
    if (!mHardware.isSupported(FEATURE_TAP_TO_WAKE)) {
      advancedPrefs.removePreference(mTapToWake);
      mTapToWake = null;
    }

    mProximityWakePreference = (SwitchPreference) findPreference(KEY_PROXIMITY_WAKE);
    boolean proximityCheckOnWake =
        getResources().getBoolean(com.android.internal.R.bool.config_proximityCheckOnWake);
    if (mProximityWakePreference != null && proximityCheckOnWake) {
      mProximityWakePreference.setOnPreferenceChangeListener(this);
    } else {
      if (advancedPrefs != null && mProximityWakePreference != null) {
        advancedPrefs.removePreference(mProximityWakePreference);
        Settings.System.putInt(getContentResolver(), Settings.System.PROXIMITY_ON_WAKE, 0);
      }
    }

    mWakeWhenPluggedOrUnplugged =
        (SwitchPreference) findPreference(KEY_WAKE_WHEN_PLUGGED_OR_UNPLUGGED);
  }
  private void updateHeaderList(List<Header> target) {
    final boolean showDev =
        mDevelopmentPreferences.getBoolean(
            DevelopmentSettings.PREF_SHOW,
            android.os.Build.TYPE.equals("eng") || android.os.Build.TYPE.equals("userdebug"));
    int i = 0;

    mHeaderIndexMap.clear();
    while (i < target.size()) {
      Header header = target.get(i);
      // Ids are integers, so downcasting
      int id = (int) header.id;
      if (id == R.id.operator_settings
          || id == R.id.manufacturer_settings
          || id == R.id.advanced_settings
          || id == R.id.hybrid_settings) {
        Utils.updateHeaderToSpecificActivityFromMetaDataOrRemove(this, target, header);
      } else if (id == R.id.launcher_settings) {
        Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
        launcherIntent.addCategory(Intent.CATEGORY_HOME);
        launcherIntent.addCategory(Intent.CATEGORY_DEFAULT);

        Intent launcherPreferencesIntent = new Intent(Intent.ACTION_MAIN);
        launcherPreferencesIntent.addCategory("com.cyanogenmod.category.LAUNCHER_PREFERENCES");

        ActivityInfo defaultLauncher =
            getPackageManager()
                .resolveActivity(launcherIntent, PackageManager.MATCH_DEFAULT_ONLY)
                .activityInfo;
        launcherPreferencesIntent.setPackage(defaultLauncher.packageName);
        ResolveInfo launcherPreferences =
            getPackageManager().resolveActivity(launcherPreferencesIntent, 0);
        if (launcherPreferences != null) {
          header.intent =
              new Intent()
                  .setClassName(
                      launcherPreferences.activityInfo.packageName,
                      launcherPreferences.activityInfo.name);
        } else {
          target.remove(header);
        }
      } else if (id == R.id.wifi_settings) {
        // Remove WiFi Settings if WiFi service is not available.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) {
          target.remove(i);
        }
      } else if (id == R.id.bluetooth_settings) {
        // Remove Bluetooth Settings if Bluetooth service is not available.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
          target.remove(i);
        }
      } else if (id == R.id.data_usage_settings) {
        // Remove data usage when kernel module not enabled
        final INetworkManagementService netManager =
            INetworkManagementService.Stub.asInterface(
                ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
        try {
          if (!netManager.isBandwidthControlEnabled()) {
            target.remove(i);
          }
        } catch (RemoteException e) {
          // ignored
        }
      } else if (id == R.id.account_settings) {
        int headerIndex = i + 1;
        i = insertAccountsHeaders(target, headerIndex);
      } else if (id == R.id.user_settings) {
        if (!UserHandle.MU_ENABLED
            || !UserManager.supportsMultipleUsers()
            || Utils.isMonkeyRunning()) {
          target.remove(i);
        }
      }

      if (target.get(i) == header
          && UserHandle.MU_ENABLED
          && UserHandle.myUserId() != 0
          && !ArrayUtils.contains(SETTINGS_FOR_RESTRICTED, id)) {
        target.remove(i);
      }

      // Increment if the current one wasn't removed by the Utils code.
      if (target.get(i) == header) {
        // Hold on to the first header, when we need to reset to the top-level
        if (mFirstHeader == null
            && HeaderAdapter.getHeaderType(header) != HeaderAdapter.HEADER_TYPE_CATEGORY) {
          mFirstHeader = header;
        }
        mHeaderIndexMap.put(id, i);
        i++;
      }
    }
  }
 /**
  * Retrieve a PendingIntent that will perform a broadcast, like calling {@link
  * Context#sendBroadcast(Intent) Context.sendBroadcast()}.
  *
  * <p class="note">For security reasons, the {@link android.content.Intent} you supply here should
  * almost always be an <em>explicit intent</em>, that is specify an explicit component to be
  * delivered to through {@link Intent#setClass(android.content.Context, Class) Intent.setClass}
  *
  * @param context The Context in which this PendingIntent should perform the broadcast.
  * @param requestCode Private request code for the sender
  * @param intent The Intent to be broadcast.
  * @param flags May be {@link #FLAG_ONE_SHOT}, {@link #FLAG_NO_CREATE}, {@link
  *     #FLAG_CANCEL_CURRENT}, {@link #FLAG_UPDATE_CURRENT}, or any of the flags as supported by
  *     {@link Intent#fillIn Intent.fillIn()} to control which unspecified parts of the intent that
  *     can be supplied when the actual send happens.
  * @return Returns an existing or new PendingIntent matching the given parameters. May return null
  *     only if {@link #FLAG_NO_CREATE} has been supplied.
  */
 public static PendingIntent getBroadcast(
     Context context, int requestCode, Intent intent, @Flags int flags) {
   return getBroadcastAsUser(
       context, requestCode, intent, flags, new UserHandle(UserHandle.myUserId()));
 }
Example #23
0
  @Override
  protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    mHandler = new MyHandler(this);

    mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

    addPreferencesFromResource(R.xml.device_info_status);
    mBatteryLevel = findPreference(KEY_BATTERY_LEVEL);
    mBatteryStatus = findPreference(KEY_BATTERY_STATUS);

    mRes = getResources();
    sUnknown = mRes.getString(R.string.device_info_default);
    if (UserHandle.myUserId() == UserHandle.USER_OWNER) {
      mPhone = PhoneFactory.getDefaultPhone();
    }
    // Note - missing in zaku build, be careful later...
    mSignalStrength = findPreference(KEY_SIGNAL_STRENGTH);
    mUptime = findPreference("up_time");

    if (mPhone == null || Utils.isWifiOnly(getApplicationContext())) {
      for (String key : PHONE_RELATED_ENTRIES) {
        removePreferenceFromScreen(key);
      }
    } else {
      // NOTE "imei" is the "Device ID" since it represents
      //  the IMEI in GSM and the MEID in CDMA
      if (mPhone.getPhoneName().equals("CDMA")) {
        setSummaryText(KEY_MEID_NUMBER, mPhone.getMeid());
        setSummaryText(KEY_MIN_NUMBER, mPhone.getCdmaMin());
        if (getResources().getBoolean(R.bool.config_msid_enable)) {
          findPreference(KEY_MIN_NUMBER).setTitle(R.string.status_msid_number);
        }
        setSummaryText(KEY_PRL_VERSION, mPhone.getCdmaPrlVersion());
        removePreferenceFromScreen(KEY_IMEI_SV);

        if (mPhone.getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE) {
          // Show ICC ID and IMEI for LTE device
          setSummaryText(KEY_ICC_ID, mPhone.getIccSerialNumber());
          setSummaryText(KEY_IMEI, mPhone.getImei());
        } else {
          // device is not GSM/UMTS, do not display GSM/UMTS features
          // check Null in case no specified preference in overlay xml
          removePreferenceFromScreen(KEY_IMEI);
          removePreferenceFromScreen(KEY_ICC_ID);
        }
      } else {
        setSummaryText(KEY_IMEI, mPhone.getDeviceId());

        setSummaryText(
            KEY_IMEI_SV,
            ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceSoftwareVersion());

        // device is not CDMA, do not display CDMA features
        // check Null in case no specified preference in overlay xml
        removePreferenceFromScreen(KEY_PRL_VERSION);
        removePreferenceFromScreen(KEY_MEID_NUMBER);
        removePreferenceFromScreen(KEY_MIN_NUMBER);
        removePreferenceFromScreen(KEY_ICC_ID);

        // only show area info when SIM country is Brazil
        if ("br".equals(mTelephonyManager.getSimCountryIso())) {
          mShowLatestAreaInfo = true;
        }
      }

      String rawNumber = mPhone.getLine1Number(); // may be null or empty
      String formattedNumber = null;
      if (!TextUtils.isEmpty(rawNumber)) {
        formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
      }
      // If formattedNumber is null or empty, it'll display as "Unknown".
      setSummaryText(KEY_PHONE_NUMBER, formattedNumber);

      mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler);
      mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED);
      mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED);

      if (!mShowLatestAreaInfo) {
        removePreferenceFromScreen(KEY_LATEST_AREA_INFO);
      }
    }

    setWimaxStatus();
    setWifiStatus();
    setBtStatus();
    setIpAddressStatus();

    String serial = Build.SERIAL;
    if (serial != null && !serial.equals("")) {
      setSummaryText(KEY_SERIAL_NUMBER, serial);
    } else {
      removePreferenceFromScreen(KEY_SERIAL_NUMBER);
    }
  }
 /**
  * Returns true if user preference is set to 24-hour format.
  *
  * @param context the context to use for the content resolver
  * @return true if 24 hour time format is selected, false otherwise.
  */
 public static boolean is24HourFormat(Context context) {
   return is24HourFormat(context, UserHandle.myUserId());
 }