Example usage for android.content Context USER_SERVICE

List of usage examples for android.content Context USER_SERVICE

Introduction

In this page you can find the example usage for android.content Context USER_SERVICE.

Prototype

String USER_SERVICE

To view the source code for android.content Context USER_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.os.UserManager for managing users on devices that support multiple users.

Usage

From source file:ch.uzh.supersede.feedbacklibrary.FeedbackActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_feedback);

    UserManager userManager = (UserManager) getApplicationContext().getSystemService(Context.USER_SERVICE);
    if (userManager.isUserAGoat()) {
        Log.v(TAG, "The user IS a goat and subject to teleportations");
    } else {/*from www . j a v a2 s.  c o  m*/
        Log.v(TAG, "The user IS NOT a goat and subject to teleportations");
    }

    Intent intent = getIntent();
    // Get the default image path for the screenshot if present
    defaultImagePath = intent.getStringExtra(DEFAULT_IMAGE_PATH);
    // Get the configuration type
    isPush = intent.getBooleanExtra(IS_PUSH_STRING, true);
    // Get values related to a pull configuration
    selectedPullConfigurationIndex = intent.getLongExtra(SELECTED_PULL_CONFIGURATION_INDEX_STRING, -1);
    String jsonString = intent.getStringExtra(JSON_CONFIGURATION_STRING);

    // Initialization based on the type of configuration, i.e., if it is push or pull
    language = intent.getStringExtra(EXTRA_KEY_LANGUAGE);
    baseURL = intent.getStringExtra(EXTRA_KEY_BASE_URL);
    if (!isPush && selectedPullConfigurationIndex != -1 && jsonString != null) {
        // The feedback activity is started on behalf of a triggered pull configuration
        Log.v(TAG, "The feedback activity is started via a PULL configuration");

        // Save the current configuration under FeedbackActivity.CONFIGURATION_DIR}/FeedbackActivity.JSON_CONFIGURATION_FILE_NAME
        Utils.saveStringContentToInternalStorage(getApplicationContext(), CONFIGURATION_DIR,
                JSON_CONFIGURATION_FILE_NAME, jsonString, MODE_PRIVATE);
        orchestratorConfigurationItem = new Gson().fromJson(jsonString, OrchestratorConfigurationItem.class);
        initModel();
        initView();
    } else {
        // The feedback activity is started on behalf of the user
        Log.v(TAG, "The feedback activity is started via a PUSH configuration");

        // TODO: remove before release
        //initOfflineConfiguration();

        // TODO: uncomment before release
        // Get the application id and language
        init(intent.getLongExtra(EXTRA_KEY_APPLICATION_ID, -1L), baseURL, language);
    }
}

From source file:com.android.packageinstaller.PackageInstallerActivity.java

@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    mPm = getPackageManager();/*from w w w .  j  a va2  s .  c om*/
    mInstaller = mPm.getPackageInstaller();
    mUserManager = (UserManager) getSystemService(Context.USER_SERVICE);

    final Intent intent = getIntent();
    mOriginatingUid = getOriginatingUid(intent);

    final Uri packageUri;

    if (PackageInstaller.ACTION_CONFIRM_PERMISSIONS.equals(intent.getAction())) {
        final int sessionId = intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1);
        final PackageInstaller.SessionInfo info = mInstaller.getSessionInfo(sessionId);
        if (info == null || !info.sealed || info.resolvedBaseCodePath == null) {
            Log.w(TAG, "Session " + mSessionId + " in funky state; ignoring");
            finish();
            return;
        }

        mSessionId = sessionId;
        packageUri = Uri.fromFile(new File(info.resolvedBaseCodePath));
        mOriginatingURI = null;
        mReferrerURI = null;
    } else {
        mSessionId = -1;
        packageUri = intent.getData();
        mOriginatingURI = intent.getParcelableExtra(Intent.EXTRA_ORIGINATING_URI);
        mReferrerURI = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
    }

    // if there's nothing to do, quietly slip into the ether
    if (packageUri == null) {
        Log.w(TAG, "Unspecified source");
        setPmResult(PackageManager.INSTALL_FAILED_INVALID_URI);
        finish();
        return;
    }

    if (DeviceUtils.isWear(this)) {
        showDialogInner(DLG_NOT_SUPPORTED_ON_WEAR);
        return;
    }

    //set view
    setContentView(R.layout.install_start);
    mInstallConfirm = findViewById(R.id.install_confirm_panel);
    mInstallConfirm.setVisibility(View.INVISIBLE);
    mOk = (Button) findViewById(R.id.ok_button);
    mCancel = (Button) findViewById(R.id.cancel_button);
    mOk.setOnClickListener(this);
    mCancel.setOnClickListener(this);

    // Block the install attempt on the Unknown Sources setting if necessary.
    final boolean requestFromUnknownSource = isInstallRequestFromUnknownSource(intent);
    if (!requestFromUnknownSource) {
        processPackageUri(packageUri);
        return;
    }

    // If the admin prohibits it, or we're running in a managed profile, just show error
    // and exit. Otherwise show an option to take the user to Settings to change the setting.
    final boolean isManagedProfile = mUserManager.isManagedProfile();
    if (!isUnknownSourcesAllowedByAdmin()) {
        startActivity(new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS));
        clearCachedApkIfNeededAndFinish();
    } else if (!isUnknownSourcesEnabled() && isManagedProfile) {
        showDialogInner(DLG_ADMIN_RESTRICTS_UNKNOWN_SOURCES);
    } else if (!isUnknownSourcesEnabled()) {
        // Ask user to enable setting first

        showDialogInner(DLG_UNKNOWN_SOURCES);
    } else {
        processPackageUri(packageUri);
    }
}

From source file:com.farmerbb.taskbar.service.StartMenuService.java

private void refreshApps(final String query, final boolean firstDraw) {
    if (thread != null)
        thread.interrupt();//w w  w  . ja va 2  s.  c  o m

    handler = new Handler();
    thread = new Thread(() -> {
        if (pm == null)
            pm = getPackageManager();

        UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) getSystemService(Context.LAUNCHER_APPS_SERVICE);

        final List<UserHandle> userHandles = userManager.getUserProfiles();
        final List<LauncherActivityInfo> unfilteredList = new ArrayList<>();

        for (UserHandle handle : userHandles) {
            unfilteredList.addAll(launcherApps.getActivityList(null, handle));
        }

        final List<LauncherActivityInfo> topAppsList = new ArrayList<>();
        final List<LauncherActivityInfo> allAppsList = new ArrayList<>();
        final List<LauncherActivityInfo> list = new ArrayList<>();

        TopApps topApps = TopApps.getInstance(StartMenuService.this);
        for (LauncherActivityInfo appInfo : unfilteredList) {
            if (topApps.isTopApp(appInfo.getComponentName().flattenToString())
                    || topApps.isTopApp(appInfo.getName()))
                topAppsList.add(appInfo);
        }

        Blacklist blacklist = Blacklist.getInstance(StartMenuService.this);
        for (LauncherActivityInfo appInfo : unfilteredList) {
            if (!(blacklist.isBlocked(appInfo.getComponentName().flattenToString())
                    || blacklist.isBlocked(appInfo.getName()))
                    && !(topApps.isTopApp(appInfo.getComponentName().flattenToString())
                            || topApps.isTopApp(appInfo.getName())))
                allAppsList.add(appInfo);
        }

        Collections.sort(topAppsList, comparator);
        Collections.sort(allAppsList, comparator);

        list.addAll(topAppsList);
        list.addAll(allAppsList);

        topAppsList.clear();
        allAppsList.clear();

        List<LauncherActivityInfo> queryList;
        if (query == null)
            queryList = list;
        else {
            queryList = new ArrayList<>();
            for (LauncherActivityInfo appInfo : list) {
                if (appInfo.getLabel().toString().toLowerCase().contains(query.toLowerCase()))
                    queryList.add(appInfo);
            }
        }

        // Now that we've generated the list of apps,
        // we need to determine if we need to redraw the start menu or not
        boolean shouldRedrawStartMenu = false;
        List<String> finalApplicationIds = new ArrayList<>();

        if (query == null && !firstDraw) {
            for (LauncherActivityInfo appInfo : queryList) {
                finalApplicationIds.add(appInfo.getApplicationInfo().packageName);
            }

            if (finalApplicationIds.size() != currentStartMenuIds.size())
                shouldRedrawStartMenu = true;
            else {
                for (int i = 0; i < finalApplicationIds.size(); i++) {
                    if (!finalApplicationIds.get(i).equals(currentStartMenuIds.get(i))) {
                        shouldRedrawStartMenu = true;
                        break;
                    }
                }
            }
        } else
            shouldRedrawStartMenu = true;

        if (shouldRedrawStartMenu) {
            if (query == null)
                currentStartMenuIds = finalApplicationIds;

            Drawable defaultIcon = pm.getDefaultActivityIcon();

            final List<AppEntry> entries = new ArrayList<>();
            for (LauncherActivityInfo appInfo : queryList) {

                // Attempt to work around frequently reported OutOfMemoryErrors
                String label;
                Drawable icon;

                try {
                    label = appInfo.getLabel().toString();
                    icon = IconCache.getInstance(StartMenuService.this).getIcon(StartMenuService.this, pm,
                            appInfo);
                } catch (OutOfMemoryError e) {
                    System.gc();

                    label = appInfo.getApplicationInfo().packageName;
                    icon = defaultIcon;
                }

                AppEntry newEntry = new AppEntry(appInfo.getApplicationInfo().packageName,
                        new ComponentName(appInfo.getApplicationInfo().packageName, appInfo.getName())
                                .flattenToString(),
                        label, icon, false);

                newEntry.setUserId(userManager.getSerialNumberForUser(appInfo.getUser()));
                entries.add(newEntry);
            }

            handler.post(() -> {
                String queryText = searchView.getQuery().toString();
                if (query == null && queryText.length() == 0 || query != null && query.equals(queryText)) {
                    StartMenuAdapter adapter;
                    SharedPreferences pref = U.getSharedPreferences(StartMenuService.this);
                    if (pref.getString("start_menu_layout", "list").equals("grid")) {
                        startMenu.setNumColumns(3);
                        adapter = new StartMenuAdapter(StartMenuService.this, R.layout.row_alt, entries);
                    } else
                        adapter = new StartMenuAdapter(StartMenuService.this, R.layout.row, entries);

                    int position = startMenu.getFirstVisiblePosition();
                    startMenu.setAdapter(adapter);
                    startMenu.setSelection(position);

                    if (adapter.getCount() > 0)
                        textView.setText(null);
                    else if (query != null)
                        textView.setText(getString(R.string.press_enter));
                    else
                        textView.setText(getString(R.string.nothing_to_see_here));
                }
            });
        }
    });

    thread.start();
}

From source file:com.afwsamples.testdpc.policy.PolicyManagementFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    mAdminComponentName = DeviceAdminReceiver.getComponentName(getActivity());
    mDevicePolicyManager = (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);
    mUserManager = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
    mTelephonyManager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    mPackageManager = getActivity().getPackageManager();
    mPackageName = getActivity().getPackageName();

    mImageUri = getStorageUri("image.jpg");
    mVideoUri = getStorageUri("video.mp4");
    super.onCreate(savedInstanceState);
}

From source file:com.landenlabs.all_devtool.SystemFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();/*from www.ja  v  a 2  s  . c om*/

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        long heapSize = Debug.getNativeHeapSize();
        // long maxHeap = Runtime.getRuntime().maxMemory();

        // ConfigurationInfo cfgInfo = actMgr.getDeviceConfigurationInfo();
        int largHeapMb = actMgr.getLargeMemoryClass();
        int heapMb = actMgr.getMemoryClass();

        MemoryInfo memInfo = new MemoryInfo();
        actMgr.getMemoryInfo(memInfo);

        final String sFmtMB = "%.2f MB";
        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("Mem Available (now)", String.format(sFmtMB, (double) memInfo.availMem / MB));
        listStr.put("Mem LowWhenOnlyAvail", String.format(sFmtMB, (double) memInfo.threshold / MB));
        if (Build.VERSION.SDK_INT >= 16) {
            listStr.put("Mem Installed", String.format(sFmtMB, (double) memInfo.totalMem / MB));
        }
        listStr.put("Heap (this app)", String.format(sFmtMB, (double) heapSize / MB));
        listStr.put("HeapMax (default)", String.format(sFmtMB, (double) heapMb));
        listStr.put("HeapMax (large)", String.format(sFmtMB, (double) largHeapMb));
        addBuild("Memory...", listStr);
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    try {
        List<ProcessErrorStateInfo> procErrList = actMgr.getProcessesInErrorState();
        int errCnt = (procErrList == null ? 0 : procErrList.size());
        procErrList = null;

        // List<RunningAppProcessInfo> procList = actMgr.getRunningAppProcesses();
        int procCnt = actMgr.getRunningAppProcesses().size();
        int srvCnt = actMgr.getRunningServices(100).size();

        Map<String, String> listStr = new TreeMap<String, String>();
        listStr.put("#Processes", String.valueOf(procCnt));
        listStr.put("#Proc With Err", String.valueOf(errCnt));
        listStr.put("#Services", String.valueOf(srvCnt));
        // Requires special permission
        //   int taskCnt = actMgr.getRunningTasks(100).size();
        //   listStr.put("#Tasks",  String.valueOf(taskCnt));
        addBuild("Processes...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Processes %s", ex.getMessage());
    }

    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();
        listStr.put("LargeIconDensity", String.valueOf(actMgr.getLauncherLargeIconDensity()));
        listStr.put("LargeIconSize", String.valueOf(actMgr.getLauncherLargeIconSize()));
        putIf(listStr, "isRunningInTestHarness", "Yes", ActivityManager.isRunningInTestHarness());
        putIf(listStr, "isUserAMonkey", "Yes", ActivityManager.isUserAMonkey());
        addBuild("Misc...", listStr);
    } catch (Exception ex) {
        m_log.e("System-Misc %s", ex.getMessage());
    }

    // --------------- Locale / Timezone -------------
    try {
        Locale ourLocale = Locale.getDefault();
        Date m_date = new Date();
        TimeZone tz = TimeZone.getDefault();

        Map<String, String> localeListStr = new LinkedHashMap<String, String>();

        localeListStr.put("Locale Name", ourLocale.getDisplayName());
        localeListStr.put(" Variant", ourLocale.getVariant());
        localeListStr.put(" Country", ourLocale.getCountry());
        localeListStr.put(" Country ISO", ourLocale.getISO3Country());
        localeListStr.put(" Language", ourLocale.getLanguage());
        localeListStr.put(" Language ISO", ourLocale.getISO3Language());
        localeListStr.put(" Language Dsp", ourLocale.getDisplayLanguage());

        localeListStr.put("TimeZoneID", tz.getID());
        localeListStr.put(" DayLightSavings", tz.useDaylightTime() ? "Yes" : "No");
        localeListStr.put(" In DLS", tz.inDaylightTime(m_date) ? "Yes" : "No");
        localeListStr.put(" Short Name", tz.getDisplayName(false, TimeZone.SHORT, ourLocale));
        localeListStr.put(" Long Name", tz.getDisplayName(false, TimeZone.LONG, ourLocale));

        addBuild("Locale TZ...", localeListStr);
    } catch (Exception ex) {
        m_log.e("Locale/TZ %s", ex.getMessage());
    }

    // --------------- Location Services -------------
    try {
        Map<String, String> listStr = new LinkedHashMap<String, String>();

        final LocationManager locMgr = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);

        GpsStatus gpsStatus = locMgr.getGpsStatus(null);
        if (gpsStatus != null) {
            listStr.put("Sec ToGetGPS", String.valueOf(gpsStatus.getTimeToFirstFix()));

            Iterable<GpsSatellite> satellites = gpsStatus.getSatellites();
            Iterator<GpsSatellite> sat = satellites.iterator();
            while (sat.hasNext()) {
                GpsSatellite satellite = sat.next();

                putIf(listStr,
                        String.format("Azm:%.0f, Elev:%.0f", satellite.getAzimuth(), satellite.getElevation()),
                        String.format("%.2f Snr", satellite.getSnr()), satellite.usedInFix());
            }
        }

        Location location = null;
        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (null == location)
                location = locMgr.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }

        if (null != location) {
            listStr.put(location.getProvider() + " lat,lng",
                    String.format("%.3f, %.3f", location.getLatitude(), location.getLongitude()));
        }
        if (listStr.size() != 0) {
            List<String> gpsProviders = locMgr.getAllProviders();
            int idx = 1;
            for (String providerName : gpsProviders) {
                LocationProvider provider = locMgr.getProvider(providerName);
                if (null != provider) {
                    listStr.put(providerName,
                            (locMgr.isProviderEnabled(providerName) ? "On " : "Off ")
                                    + String.format("Accuracy:%d Pwr:%d", provider.getAccuracy(),
                                            provider.getPowerRequirement()));
                }
            }
            addBuild("GPS...", listStr);
        } else
            addBuild("GPS", "Off");
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Application Info -------------
    ApplicationInfo appInfo = getActivity().getApplicationInfo();
    if (null != appInfo) {
        Map<String, String> appList = new LinkedHashMap<String, String>();
        try {
            appList.put("ProcName", appInfo.processName);
            appList.put("PkgName", appInfo.packageName);
            appList.put("DataDir", appInfo.dataDir);
            appList.put("SrcDir", appInfo.sourceDir);
            //    appList.put("PkgResDir", getActivity().getPackageResourcePath());
            //     appList.put("PkgCodeDir", getActivity().getPackageCodePath());
            String[] dbList = getActivity().databaseList();
            if (dbList != null && dbList.length != 0)
                appList.put("DataBase", dbList[0]);
            // getActivity().getComponentName().

        } catch (Exception ex) {
        }
        addBuild("AppInfo...", appList);
    }

    // --------------- Account Services -------------
    final AccountManager accMgr = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
    if (null != accMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        try {
            for (Account account : accMgr.getAccounts()) {
                strList.put(account.name, account.type);
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Accounts...", strList);
    }

    // --------------- Package Features -------------
    PackageManager pm = getActivity().getPackageManager();
    FeatureInfo[] features = pm.getSystemAvailableFeatures();
    if (features != null) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        for (FeatureInfo featureInfo : features) {
            strList.put(featureInfo.name, "");
        }
        addBuild("Features...", strList);
    }

    // --------------- Sensor Services -------------
    final SensorManager senMgr = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    if (null != senMgr) {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        // Sensor accelerometer = senMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        // senMgr.registerListener(foo, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        List<Sensor> listSensor = senMgr.getSensorList(Sensor.TYPE_ALL);
        try {
            for (Sensor sensor : listSensor) {
                strList.put(sensor.getName(), sensor.getVendor());
            }
        } catch (Exception ex) {
            m_log.e(ex.getMessage());
        }
        addBuild("Sensors...", strList);
    }

    try {
        if (Build.VERSION.SDK_INT >= 17) {
            final UserManager userMgr = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
            if (null != userMgr) {
                try {
                    addBuild("UserName", userMgr.getUserName());
                } catch (Exception ex) {
                    m_log.e(ex.getMessage());
                }
            }
        }
    } catch (Exception ex) {
    }

    try {
        Map<String, String> strList = new LinkedHashMap<String, String>();
        int screenTimeout = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.SCREEN_OFF_TIMEOUT);
        strList.put("ScreenTimeOut", String.valueOf(screenTimeout / 1000));
        int rotate = Settings.System.getInt(getActivity().getContentResolver(),
                Settings.System.ACCELEROMETER_ROTATION);
        strList.put("RotateEnabled", String.valueOf(rotate));
        if (Build.VERSION.SDK_INT >= 17) {
            // Global added in API 17
            int adb = Settings.Global.getInt(getActivity().getContentResolver(), Settings.Global.ADB_ENABLED);
            strList.put("AdbEnabled", String.valueOf(adb));
        }
        addBuild("Settings...", strList);
    } catch (Exception ex) {
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}

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. j  av a2 s.  com
    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++;
        }
    }
}

From source file:com.farmerbb.taskbar.service.TaskbarService.java

@SuppressWarnings("Convert2streamapi")
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private void updateRecentApps(final boolean firstRefresh) {
    SharedPreferences pref = U.getSharedPreferences(this);
    final PackageManager pm = getPackageManager();
    final List<AppEntry> entries = new ArrayList<>();
    List<LauncherActivityInfo> launcherAppCache = new ArrayList<>();
    int maxNumOfEntries = U.getMaxNumOfEntries(this);
    int realNumOfPinnedApps = 0;
    boolean fullLength = pref.getBoolean("full_length", false);

    PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);
    List<AppEntry> pinnedApps = pba.getPinnedApps();
    List<AppEntry> blockedApps = pba.getBlockedApps();
    List<String> applicationIdsToRemove = new ArrayList<>();

    // Filter out anything on the pinned/blocked apps lists
    if (pinnedApps.size() > 0) {
        UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);

        for (AppEntry entry : pinnedApps) {
            boolean packageEnabled = launcherApps.isPackageEnabled(entry.getPackageName(),
                    userManager.getUserForSerialNumber(entry.getUserId(this)));

            if (packageEnabled)
                entries.add(entry);/*from w w  w.j a  va2  s .  com*/
            else
                realNumOfPinnedApps--;

            applicationIdsToRemove.add(entry.getPackageName());
        }

        realNumOfPinnedApps = realNumOfPinnedApps + pinnedApps.size();
    }

    if (blockedApps.size() > 0) {
        for (AppEntry entry : blockedApps) {
            applicationIdsToRemove.add(entry.getPackageName());
        }
    }

    // Get list of all recently used apps
    List<AppEntry> usageStatsList = realNumOfPinnedApps < maxNumOfEntries ? getAppEntries() : new ArrayList<>();
    if (usageStatsList.size() > 0 || realNumOfPinnedApps > 0 || fullLength) {
        if (realNumOfPinnedApps < maxNumOfEntries) {
            List<AppEntry> usageStatsList2 = new ArrayList<>();
            List<AppEntry> usageStatsList3 = new ArrayList<>();
            List<AppEntry> usageStatsList4 = new ArrayList<>();
            List<AppEntry> usageStatsList5 = new ArrayList<>();
            List<AppEntry> usageStatsList6;

            Intent homeIntent = new Intent(Intent.ACTION_MAIN);
            homeIntent.addCategory(Intent.CATEGORY_HOME);
            ResolveInfo defaultLauncher = pm.resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY);

            // Filter out apps without a launcher intent
            // Also filter out the current launcher, and Taskbar itself
            for (AppEntry packageInfo : usageStatsList) {
                if (hasLauncherIntent(packageInfo.getPackageName())
                        && !packageInfo.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID)
                        && !packageInfo.getPackageName().equals(defaultLauncher.activityInfo.packageName))
                    usageStatsList2.add(packageInfo);
            }

            // Filter out apps that don't fall within our current search interval
            for (AppEntry stats : usageStatsList2) {
                if (stats.getLastTimeUsed() > searchInterval || runningAppsOnly)
                    usageStatsList3.add(stats);
            }

            // Sort apps by either most recently used, or most time used
            if (!runningAppsOnly) {
                if (sortOrder.contains("most_used")) {
                    Collections.sort(usageStatsList3, (us1, us2) -> Long.compare(us2.getTotalTimeInForeground(),
                            us1.getTotalTimeInForeground()));
                } else {
                    Collections.sort(usageStatsList3,
                            (us1, us2) -> Long.compare(us2.getLastTimeUsed(), us1.getLastTimeUsed()));
                }
            }

            // Filter out any duplicate entries
            List<String> applicationIds = new ArrayList<>();
            for (AppEntry stats : usageStatsList3) {
                if (!applicationIds.contains(stats.getPackageName())) {
                    usageStatsList4.add(stats);
                    applicationIds.add(stats.getPackageName());
                }
            }

            // Filter out the currently running foreground app, if requested by the user
            if (pref.getBoolean("hide_foreground", false)) {
                UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(
                        USAGE_STATS_SERVICE);
                UsageEvents events = mUsageStatsManager.queryEvents(searchInterval, System.currentTimeMillis());
                UsageEvents.Event eventCache = new UsageEvents.Event();
                String currentForegroundApp = null;

                while (events.hasNextEvent()) {
                    events.getNextEvent(eventCache);

                    if (eventCache.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                        if (!(eventCache.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID)
                                && !eventCache.getClassName().equals(MainActivity.class.getCanonicalName())
                                && !eventCache.getClassName().equals(HomeActivity.class.getCanonicalName())
                                && !eventCache.getClassName()
                                        .equals(InvisibleActivityFreeform.class.getCanonicalName())))
                            currentForegroundApp = eventCache.getPackageName();
                    }
                }

                if (!applicationIdsToRemove.contains(currentForegroundApp))
                    applicationIdsToRemove.add(currentForegroundApp);
            }

            for (AppEntry stats : usageStatsList4) {
                if (!applicationIdsToRemove.contains(stats.getPackageName())) {
                    usageStatsList5.add(stats);
                }
            }

            // Truncate list to a maximum length
            if (usageStatsList5.size() > maxNumOfEntries)
                usageStatsList6 = usageStatsList5.subList(0, maxNumOfEntries);
            else
                usageStatsList6 = usageStatsList5;

            // Determine if we need to reverse the order
            boolean needToReverseOrder;
            switch (U.getTaskbarPosition(this)) {
            case "bottom_right":
            case "top_right":
                needToReverseOrder = sortOrder.contains("false");
                break;
            default:
                needToReverseOrder = sortOrder.contains("true");
                break;
            }

            if (needToReverseOrder) {
                Collections.reverse(usageStatsList6);
            }

            // Generate the AppEntries for TaskbarAdapter
            int number = usageStatsList6.size() == maxNumOfEntries
                    ? usageStatsList6.size() - realNumOfPinnedApps
                    : usageStatsList6.size();

            UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
            LauncherApps launcherApps = (LauncherApps) getSystemService(Context.LAUNCHER_APPS_SERVICE);

            final List<UserHandle> userHandles = userManager.getUserProfiles();

            for (int i = 0; i < number; i++) {
                for (UserHandle handle : userHandles) {
                    String packageName = usageStatsList6.get(i).getPackageName();
                    List<LauncherActivityInfo> list = launcherApps.getActivityList(packageName, handle);
                    if (!list.isEmpty()) {
                        // Google App workaround
                        if (!packageName.equals("com.google.android.googlequicksearchbox"))
                            launcherAppCache.add(list.get(0));
                        else {
                            boolean added = false;
                            for (LauncherActivityInfo info : list) {
                                if (info.getName()
                                        .equals("com.google.android.googlequicksearchbox.SearchActivity")) {
                                    launcherAppCache.add(info);
                                    added = true;
                                }
                            }

                            if (!added)
                                launcherAppCache.add(list.get(0));
                        }

                        AppEntry newEntry = new AppEntry(packageName, null, null, null, false);

                        newEntry.setUserId(userManager.getSerialNumberForUser(handle));
                        entries.add(newEntry);

                        break;
                    }
                }
            }
        }

        while (entries.size() > maxNumOfEntries) {
            try {
                entries.remove(entries.size() - 1);
                launcherAppCache.remove(launcherAppCache.size() - 1);
            } catch (ArrayIndexOutOfBoundsException e) {
                /* Gracefully fail */ }
        }

        // Determine if we need to reverse the order again
        if (U.getTaskbarPosition(this).contains("vertical")) {
            Collections.reverse(entries);
            Collections.reverse(launcherAppCache);
        }

        // Now that we've generated the list of apps,
        // we need to determine if we need to redraw the Taskbar or not
        boolean shouldRedrawTaskbar = firstRefresh;

        List<String> finalApplicationIds = new ArrayList<>();
        for (AppEntry entry : entries) {
            finalApplicationIds.add(entry.getPackageName());
        }

        if (finalApplicationIds.size() != currentTaskbarIds.size() || numOfPinnedApps != realNumOfPinnedApps)
            shouldRedrawTaskbar = true;
        else {
            for (int i = 0; i < finalApplicationIds.size(); i++) {
                if (!finalApplicationIds.get(i).equals(currentTaskbarIds.get(i))) {
                    shouldRedrawTaskbar = true;
                    break;
                }
            }
        }

        if (shouldRedrawTaskbar) {
            currentTaskbarIds = finalApplicationIds;
            numOfPinnedApps = realNumOfPinnedApps;

            UserManager userManager = (UserManager) getSystemService(USER_SERVICE);

            int launcherAppCachePos = -1;
            for (int i = 0; i < entries.size(); i++) {
                if (entries.get(i).getComponentName() == null) {
                    launcherAppCachePos++;
                    LauncherActivityInfo appInfo = launcherAppCache.get(launcherAppCachePos);
                    String packageName = entries.get(i).getPackageName();

                    entries.remove(i);

                    AppEntry newEntry = new AppEntry(packageName, appInfo.getComponentName().flattenToString(),
                            appInfo.getLabel().toString(), IconCache.getInstance(TaskbarService.this)
                                    .getIcon(TaskbarService.this, pm, appInfo),
                            false);

                    newEntry.setUserId(userManager.getSerialNumberForUser(appInfo.getUser()));
                    entries.add(i, newEntry);
                }
            }

            final int numOfEntries = Math.min(entries.size(), maxNumOfEntries);

            handler.post(() -> {
                if (numOfEntries > 0 || fullLength) {
                    ViewGroup.LayoutParams params = scrollView.getLayoutParams();
                    DisplayMetrics metrics = getResources().getDisplayMetrics();
                    int recentsSize = getResources().getDimensionPixelSize(R.dimen.icon_size) * numOfEntries;
                    float maxRecentsSize = fullLength ? Float.MAX_VALUE : recentsSize;

                    if (U.getTaskbarPosition(TaskbarService.this).contains("vertical")) {
                        int maxScreenSize = metrics.heightPixels - U.getStatusBarHeight(TaskbarService.this)
                                - U.getBaseTaskbarSize(TaskbarService.this);

                        params.height = (int) Math.min(maxRecentsSize, maxScreenSize)
                                + getResources().getDimensionPixelSize(R.dimen.divider_size);

                        if (fullLength && U.getTaskbarPosition(this).contains("bottom")) {
                            try {
                                Space whitespace = (Space) layout.findViewById(R.id.whitespace);
                                ViewGroup.LayoutParams params2 = whitespace.getLayoutParams();
                                params2.height = maxScreenSize - recentsSize;
                                whitespace.setLayoutParams(params2);
                            } catch (NullPointerException e) {
                                /* Gracefully fail */ }
                        }
                    } else {
                        int maxScreenSize = metrics.widthPixels - U.getBaseTaskbarSize(TaskbarService.this);

                        params.width = (int) Math.min(maxRecentsSize, maxScreenSize)
                                + getResources().getDimensionPixelSize(R.dimen.divider_size);

                        if (fullLength && U.getTaskbarPosition(this).contains("right")) {
                            try {
                                Space whitespace = (Space) layout.findViewById(R.id.whitespace);
                                ViewGroup.LayoutParams params2 = whitespace.getLayoutParams();
                                params2.width = maxScreenSize - recentsSize;
                                whitespace.setLayoutParams(params2);
                            } catch (NullPointerException e) {
                                /* Gracefully fail */ }
                        }
                    }

                    scrollView.setLayoutParams(params);

                    taskbar.removeAllViews();
                    for (int i = 0; i < entries.size(); i++) {
                        taskbar.addView(getView(entries, i));
                    }

                    isShowingRecents = true;
                    if (shouldRefreshRecents && scrollView.getVisibility() != View.VISIBLE) {
                        if (firstRefresh)
                            scrollView.setVisibility(View.INVISIBLE);
                        else
                            scrollView.setVisibility(View.VISIBLE);
                    }

                    if (firstRefresh && scrollView.getVisibility() != View.VISIBLE)
                        new Handler().post(() -> {
                            switch (U.getTaskbarPosition(TaskbarService.this)) {
                            case "bottom_left":
                            case "bottom_right":
                            case "top_left":
                            case "top_right":
                                if (sortOrder.contains("false"))
                                    scrollView.scrollTo(0, 0);
                                else if (sortOrder.contains("true"))
                                    scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight());
                                break;
                            case "bottom_vertical_left":
                            case "bottom_vertical_right":
                            case "top_vertical_left":
                            case "top_vertical_right":
                                if (sortOrder.contains("false"))
                                    scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight());
                                else if (sortOrder.contains("true"))
                                    scrollView.scrollTo(0, 0);
                                break;
                            }

                            if (shouldRefreshRecents) {
                                scrollView.setVisibility(View.VISIBLE);
                            }
                        });
                } else {
                    isShowingRecents = false;
                    scrollView.setVisibility(View.GONE);
                }
            });
        }
    } else if (firstRefresh || currentTaskbarIds.size() > 0) {
        currentTaskbarIds.clear();
        handler.post(() -> {
            isShowingRecents = false;
            scrollView.setVisibility(View.GONE);
        });
    }
}

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

public void updateHeaderList(List<Header> target) {
    final boolean showDev = mDevelopmentPreferences.getBoolean(DevelopmentSettings.PREF_SHOW,
            android.os.Build.TYPE.equals("eng"));
    int i = 0;/*  ww w  . j  a va2  s.c  om*/
    boolean IsSupVoice = 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) {
            target.remove(header);
        }
        /* @} */
        /*
        else if (id == R.id.mobile_network_settings_hw){
              header.intent.putExtra(MobileSimChoose.PACKAGE_NAME,
               "com.android.phone");
              header.intent.putExtra(MobileSimChoose.CLASS_NAME,
               "com.android.phone.MobileNetworkSettings");
        }
        */
        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++;
        }
    }
}

From source file:com.android.server.MountService.java

private boolean hasUserRestriction(String restriction) {
    UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
    return um.hasUserRestriction(restriction, Binder.getCallingUserHandle());
}

From source file:com.jtschohl.androidfirewall.MainActivity.java

@SuppressLint("NewApi")
public void isCurrentUserOwner(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        try {// ww  w  . j  a v a 2 s. co  m
            Method getUserHandle = UserManager.class.getMethod("getUserHandle");
            int userHandle = (Integer) getUserHandle.invoke(context.getSystemService(Context.USER_SERVICE));
            Log.d(TAG, String.format("Found user value = %d", userHandle));
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong("userID", userHandle);
            editor.commit();
        } catch (Exception e) {
            Log.d(TAG, "Exception on isCurrentUserOwner " + e.getMessage());
        }
    }
}