Example usage for android.os UserHandle myUserId

List of usage examples for android.os UserHandle myUserId

Introduction

In this page you can find the example usage for android.os UserHandle myUserId.

Prototype

@SystemApi
public static @UserIdInt int myUserId() 

Source Link

Document

Returns the user id of the current process

Usage

From source file:com.android.settingslib.RestrictedPreference.java

public void checkRestrictionAndSetDisabled(String userRestriction) {
    mHelper.checkRestrictionAndSetDisabled(userRestriction, UserHandle.myUserId());
}

From source file:com.android.settings.applications.ClearDefaultsPreference.java

@Override
public void onBindViewHolder(final PreferenceViewHolder view) {
    super.onBindViewHolder(view);

    mActivitiesButton = (Button) view.findViewById(R.id.clear_activities_button);
    mActivitiesButton.setOnClickListener(new View.OnClickListener() {
        @Override//w  w  w.j  a va2s .co m
        public void onClick(View v) {
            if (mUsbManager != null) {
                final int userId = UserHandle.myUserId();
                mPm.clearPackagePreferredActivities(mPackageName);
                if (isDefaultBrowser(mPackageName)) {
                    mPm.setDefaultBrowserPackageNameAsUser(null, userId);
                }
                try {
                    mUsbManager.clearDefaults(mPackageName, userId);
                } catch (RemoteException e) {
                    Log.e(TAG, "mUsbManager.clearDefaults", e);
                }
                mAppWidgetManager.setBindAppWidgetPermission(mPackageName, false);
                TextView autoLaunchView = (TextView) view.findViewById(R.id.auto_launch);
                resetLaunchDefaultsUi(autoLaunchView);
            }
        }
    });

    updateUI(view);
}

From source file:com.android.tv.settings.MainFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    mAuthenticatorHelper = new AuthenticatorHelper(getContext(), new UserHandle(UserHandle.myUserId()),
            new AuthenticatorHelper.OnAccountsUpdateListener() {
                @Override/* w ww. j  a va 2  s  .co  m*/
                public void onAccountsUpdate(UserHandle userHandle) {
                    updateAccounts();
                }
            });
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    mConnectivityListener = new ConnectivityListener(getContext(), new ConnectivityListener.Listener() {
        @Override
        public void onConnectivityChange() {
            updateWifi();
        }
    });

    final TvInputManager manager = (TvInputManager) getContext().getSystemService(Context.TV_INPUT_SERVICE);
    if (manager != null) {
        for (final TvInputInfo input : manager.getTvInputList()) {
            if (input.isPassthroughInput()) {
                mInputSettingNeeded = true;
            }
        }
    }
    super.onCreate(savedInstanceState);
}

From source file:com.android.settings.applications.ClearDefaultsPreference.java

private boolean isDefaultBrowser(String packageName) {
    final String defaultBrowser = mPm.getDefaultBrowserPackageNameAsUser(UserHandle.myUserId());
    return packageName.equals(defaultBrowser);
}

From source file:com.android.managedprovisioning.DeviceOwnerProvisioningService.java

/**
 * This is the core method of this class. It goes through every provisioning step.
 * Each task checks if it is required and executes if it is.
 *///www.j  a  va2 s .c om
private void startDeviceOwnerProvisioning(final ProvisioningParams params) {
    if (DEBUG)
        ProvisionLogger.logd("Starting device owner provisioning");

    // Construct Tasks. Do not start them yet.
    mAddWifiNetworkTask = new AddWifiNetworkTask(this, params.wifiInfo, new AddWifiNetworkTask.Callback() {
        @Override
        public void onSuccess() {
            progressUpdate(R.string.progress_download);
            mDownloadPackageTask.run();
        }

        @Override
        public void onError() {
            error(R.string.device_owner_error_wifi, false /* do not require factory reset */);
        }
    });

    mDownloadPackageTask = new DownloadPackageTask(this, new DownloadPackageTask.Callback() {
        @Override
        public void onSuccess() {
            progressUpdate(R.string.progress_install);
            mInstallPackageTask.addInstallIfNecessary(params.inferDeviceAdminPackageName(),
                    mDownloadPackageTask.getDownloadedPackageLocation(DEVICE_OWNER));
            mInstallPackageTask.run();
        }

        @Override
        public void onError(int errorCode) {
            switch (errorCode) {
            case DownloadPackageTask.ERROR_HASH_MISMATCH:
                error(R.string.device_owner_error_hash_mismatch);
                break;
            case DownloadPackageTask.ERROR_DOWNLOAD_FAILED:
                error(R.string.device_owner_error_download_failed);
                break;
            default:
                error(R.string.device_owner_error_general);
                break;
            }
        }
    });

    // Add packages to download to the DownloadPackageTask.
    mDownloadPackageTask.addDownloadIfNecessary(params.inferDeviceAdminPackageName(),
            params.deviceAdminDownloadInfo, DEVICE_OWNER);

    mInstallPackageTask = new InstallPackageTask(this, new InstallPackageTask.Callback() {
        @Override
        public void onSuccess() {
            progressUpdate(R.string.progress_set_owner);
            try {
                // Now that the app has been installed, we can look for the device admin
                // component in it.
                mSetDevicePolicyTask
                        .run(mParams.inferDeviceAdminComponentName(DeviceOwnerProvisioningService.this));
            } catch (IllegalProvisioningArgumentException e) {
                error(R.string.device_owner_error_general);
                ProvisionLogger.loge("Failed to infer the device admin component name", e);
                return;
            }
        }

        @Override
        public void onError(int errorCode) {
            switch (errorCode) {
            case InstallPackageTask.ERROR_PACKAGE_INVALID:
                error(R.string.device_owner_error_package_invalid);
                break;
            case InstallPackageTask.ERROR_INSTALLATION_FAILED:
                error(R.string.device_owner_error_installation_failed);
                break;
            default:
                error(R.string.device_owner_error_general);
                break;
            }
        }
    });

    mSetDevicePolicyTask = new SetDevicePolicyTask(this,
            getResources().getString(R.string.default_owned_device_username),
            new SetDevicePolicyTask.Callback() {
                @Override
                public void onSuccess() {
                    mDeleteNonRequiredAppsTask.run();
                }

                @Override
                public void onError() {
                    error(R.string.device_owner_error_general);
                }
            });

    // For split system user devices that will have a system device owner, don't adjust the set
    // of enabled packages in the system user as we expect the right set of packages to be
    // enabled for the system user out of the box. For other devices, the set of available
    // packages can vary depending on management state.
    boolean leaveAllSystemAppsEnabled = params.leaveAllSystemAppsEnabled
            || params.provisioningAction.equals(ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE);
    mDeleteNonRequiredAppsTask = new DeleteNonRequiredAppsTask(this, params.inferDeviceAdminPackageName(),
            DeleteNonRequiredAppsTask.DEVICE_OWNER, true /* creating new profile */, UserHandle.myUserId(),
            leaveAllSystemAppsEnabled, new DeleteNonRequiredAppsTask.Callback() {
                @Override
                public void onSuccess() {
                    mDisallowAddUserTask.maybeDisallowAddUsers();

                    // Done with provisioning. Success.
                    onProvisioningSuccess();
                }

                @Override
                public void onError() {
                    error(R.string.device_owner_error_general);
                }
            });

    mDisallowAddUserTask = new DisallowAddUserTask((UserManager) getSystemService(USER_SERVICE),
            UserHandle.myUserId(), UserManager.isSplitSystemUser());

    // Start first task, which starts next task in its callback, etc.
    progressUpdate(R.string.progress_connect_to_wifi);
    mAddWifiNetworkTask.run();
}

From source file:com.android.car.trust.CarBleTrustAgent.java

private UserHandle getCurrentUserHandle() {
    return UserHandle.of(UserHandle.myUserId());
}

From source file:com.jedi.setupwizard.ui.SetupWizardActivity.java

private void finishSetup() {
    if (mSetupComplete)
        return;//from w w  w. ja  v a 2s . c om
    mSetupComplete = true;
    boolean applyingDefaultTheme = handleDefaultThemeSetup();

    Settings.Global.putInt(getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 1);
    Settings.Secure.putInt(getContentResolver(), Settings.Secure.USER_SETUP_COMPLETE, 1);
    UserManager.get(this).setUserName(UserHandle.myUserId(),
            getString(com.android.internal.R.string.owner_name));
    ((SetupWizard) AppGlobals.getInitialApplication()).enableStatusBar();
    if (!applyingDefaultTheme) {
        finalizeSetup();
    } else {
        showDialog(DIALOG_FINISHING);
    }
}

From source file:com.android.settings.accessibility.AccessibilitySettings.java

private void updateServicePreferences() {
    // 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./* w  w  w.  ja  v a  2 s .c o m*/
    ArrayList<Preference> servicePreferences = new ArrayList<>(
            mServicePreferenceToPreferenceCategoryMap.keySet());
    for (int i = 0; i < servicePreferences.size(); i++) {
        Preference service = servicePreferences.get(i);
        PreferenceCategory category = mServicePreferenceToPreferenceCategoryMap.get(service);
        category.removePreference(service);
    }

    initializePreBundledServicesMapFromArray(CATEGORY_SCREEN_READER,
            R.array.config_preinstalled_screen_reader_services);
    initializePreBundledServicesMapFromArray(CATEGORY_AUDIO_AND_CAPTIONS,
            R.array.config_preinstalled_audio_and_caption_services);
    initializePreBundledServicesMapFromArray(CATEGORY_DISPLAY, R.array.config_preinstalled_display_services);
    initializePreBundledServicesMapFromArray(CATEGORY_INTERACTION_CONTROL,
            R.array.config_preinstalled_interaction_control_services);

    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;

    PreferenceCategory downloadedServicesCategory = mCategoryToPrefCategoryMap
            .get(CATEGORY_DOWNLOADED_SERVICES);
    // Temporarily add the downloaded services category back if it was previously removed.
    if (findPreference(CATEGORY_DOWNLOADED_SERVICES) == null) {
        getPreferenceScreen().addPreference(downloadedServicesCategory);
    }

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

        RestrictedPreference preference = new RestrictedPreference(downloadedServicesCategory.getContext());
        String title = info.getResolveInfo().loadLabel(getPackageManager()).toString();

        Drawable icon;
        if (info.getResolveInfo().getIconResource() == 0) {
            icon = ContextCompat.getDrawable(getContext(), R.mipmap.ic_accessibility_generic);
        } else {
            icon = info.getResolveInfo().loadIcon(getPackageManager());
        }

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

        preference.setKey(componentName.flattenToString());

        preference.setTitle(title);
        preference.setIcon(icon);
        final boolean serviceEnabled = accessibilityEnabled && enabledServices.contains(componentName);
        final String serviceState = serviceEnabled ? getString(R.string.accessibility_summary_state_enabled)
                : getString(R.string.accessibility_summary_state_disabled);
        final CharSequence serviceSummary = info.loadSummary(getPackageManager());
        final String stateSummaryCombo = getString(R.string.accessibility_summary_default_combination,
                serviceState, serviceSummary);
        preference.setSummary((TextUtils.isEmpty(serviceSummary)) ? serviceState : stateSummaryCombo);

        // Disable all accessibility services that are not permitted.
        boolean serviceAllowed = permittedServices == null || permittedServices.contains(packageName);
        if (!serviceAllowed && !serviceEnabled) {
            EnforcedAdmin admin = RestrictedLockUtils.checkIfAccessibilityServiceDisallowed(getActivity(),
                    packageName, UserHandle.myUserId());
            if (admin != null) {
                preference.setDisabledByAdmin(admin);
            } else {
                preference.setEnabled(false);
            }
        } else {
            preference.setEnabled(true);
        }

        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(packageName, settingsClassName).flattenToString());
        }
        extras.putParcelable(EXTRA_COMPONENT_NAME, componentName);

        PreferenceCategory prefCategory = downloadedServicesCategory;
        // Set the appropriate category if the service comes pre-installed.
        if (mPreBundledServiceComponentToCategoryMap.containsKey(componentName)) {
            prefCategory = mPreBundledServiceComponentToCategoryMap.get(componentName);
        }
        preference.setOrder(FIRST_PREFERENCE_IN_CATEGORY_INDEX);
        prefCategory.addPreference(preference);
        mServicePreferenceToPreferenceCategoryMap.put(preference, prefCategory);
    }

    // If the user has not installed any additional services, hide the category.
    if (downloadedServicesCategory.getPreferenceCount() == 0) {
        PreferenceScreen screen = getPreferenceScreen();
        screen.removePreference(downloadedServicesCategory);
    }
}

From source file:com.android.settings.accessibility.AccessibilitySettings.java

private void updateAccessibilityShortcut(Preference preference) {
    if (AccessibilityManager.getInstance(getActivity()).getInstalledAccessibilityServiceList().isEmpty()) {
        mAccessibilityShortcutPreferenceScreen
                .setSummary(getString(R.string.accessibility_no_services_installed));
        mAccessibilityShortcutPreferenceScreen.setEnabled(false);
    } else {/* w ww. j av a2  s .  c o  m*/
        mAccessibilityShortcutPreferenceScreen.setEnabled(true);
        boolean shortcutEnabled = AccessibilityUtils.isShortcutEnabled(getContext(), UserHandle.myUserId());
        CharSequence summary = shortcutEnabled
                ? AccessibilityShortcutPreferenceFragment.getServiceName(getContext())
                : getString(R.string.accessibility_feature_state_off);
        mAccessibilityShortcutPreferenceScreen.setSummary(summary);
    }
}

From source file:com.android.settings.Settings.java

private void updateHeaderList(List<Header> target) {
    final boolean showDev = mDevelopmentPreferences.getBoolean(DevelopmentSettings.PREF_SHOW,
            android.os.Build.TYPE.equals("eng"));
    int i = 0;//from  w w w. ja v  a  2s.c o  m
    boolean IsSupVoice = Settings.this.getResources()
            .getBoolean(com.android.internal.R.bool.config_voice_capable);
    final UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
    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) {
            Utils.updateHeaderToSpecificActivityFromMetaDataOrRemove(this, target, 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 {
                /* SPRDADD to delete the data usage item of settings @{ */
                boolean support_cmcc = SystemProperties.get("ro.operator").equals("cmcc");
                if (!netManager.isBandwidthControlEnabled() || support_cmcc) {
                    target.remove(i);
                }
            } catch (RemoteException e) {
                // ignored
            }
        } else if (id == R.id.battery_settings) {
            // Remove battery settings when battery is not available. (e.g. TV)

            if (!mBatteryPresent) {
                target.remove(i);
            }
            /* @} */
        } else if (id == R.id.account_settings) {
            int headerIndex = i + 1;
            i = insertAccountsHeaders(target, headerIndex);
            // SPRD: clear viewCache
            ListAdapter listAdapter = getListAdapter();
            if (listAdapter instanceof HeaderAdapter) {
                // add for tab style
                ((HeaderAdapter) listAdapter).flushViewCache();
            }
        } else if (id == R.id.home_settings) {
            if (!updateHomeSettingHeaders(header)) {
                target.remove(i);
            }
        } else if (id == R.id.user_settings) {
            if (!UserHandle.MU_ENABLED || !UserManager.supportsMultipleUsers() || Utils.isMonkeyRunning()) {
                target.remove(i);
            }
        } else if (id == R.id.nfc_payment_settings) {
            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)) {
                target.remove(i);
            } else {
                // Only show if NFC is on and we have the HCE feature
                NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
                if (!adapter.isEnabled() || !getPackageManager()
                        .hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)) {
                    target.remove(i);
                }
            }
        } else if (id == R.id.development_settings) {
            if (!showDev) {
                target.remove(i);
            }
        } else if (id == R.id.account_add) {
            if (um.hasUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
                target.remove(i);
            }
        }

        /* SPRD: modified for cucc feature @{ */
        else if (id == R.id.network_preference_settings) {
            //if (!("cucc".equals(WifiManager.SUPPORT_VERSION))) {
            if (!CU_SUPPORT) { //modify for CUCC support  2013-11-22
                target.remove(header);
            }
        }
        /* @} */
        /* SPRD: add AudioProfile  @{ */
        else if (id == R.id.sound_settings && IsSupVoice) {
            target.remove(header);
        } else if (id == R.id.audio_profiles && !IsSupVoice) {
            target.remove(header);
        }
        /* @} */
        /* SPRD: for multi-sim @{ */
        else if (id == R.id.dual_sim_settings) {
            if (!TelephonyManager.isMultiSim() || (!mVoiceCapable)) {
                target.remove(header);
            }
        }
        /* @} */
        /* SPRD: add for uui style 335009 @{ */
        else if (id == R.id.uninstall_settings) {
            if (!UNIVERSEUI_SUPPORT) {
                target.remove(header);
            }
        }
        /* @} */
        /* smart_wake {@*/
        else if (id == R.id.smart_wake) {
            if (!SMART_WAKE) {
                target.remove(header);
            }
        }
        /* @} */
        /*lyx 20150320 power_saving */
        else if (id == R.id.power_saving) {
            if (!FeatureOption.PRJ_FEATURE_POWER_SAVING) {
                target.remove(header);
            }
        }
        /* @} */
        if (i < target.size() && 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 (i < target.size() && 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++;
        }
    }
}