Java Code Examples for android.content.pm.PackageManager#GET_UNINSTALLED_PACKAGES

The following examples show how to use android.content.pm.PackageManager#GET_UNINSTALLED_PACKAGES . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GridSizeMigrationTask.java    From LaunchEnr with GNU General Public License v3.0 6 votes vote down vote up
protected static HashSet<String> getValidPackages(Context context) {
    // Initialize list of valid packages. This contain all the packages which are already on
    // the device and packages which are being installed. Any item which doesn't belong to
    // this set is removed.
    // Since the loader removes such items anyway, removing these items here doesn't cause
    // any extra data loss and gives us more free space on the grid for better migration.
    HashSet validPackages = new HashSet<>();
    int uninstalled = android.os.Build.VERSION.SDK_INT >= 24 ? PackageManager.MATCH_UNINSTALLED_PACKAGES : PackageManager.GET_UNINSTALLED_PACKAGES;

    for (PackageInfo info : context.getPackageManager()
            .getInstalledPackages(uninstalled)) {
        validPackages.add(info.packageName);
    }
    validPackages.addAll(PackageInstallerCompat.getInstance(context)
            .updateAndGetActiveSessionCache().keySet());
    return validPackages;
}
 
Example 2
Source File: UninstallDropTarget.java    From LaunchEnr with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Notifies the {@param callback} whether the uninstall was successful or not.
 *
 * Since there is no direct callback for an uninstall request, we check the package existence
 * when the launch resumes next time. This assumes that the uninstall activity will finish only
 * after the task is completed
 */
protected static void sendUninstallResult(
        final Launcher launcher, boolean activityStarted,
        final ComponentName cn, final UserHandle user,
        final DropTargetResultCallback callback) {
    if (activityStarted)  {
        final Runnable checkIfUninstallWasSuccess = new Runnable() {
            @Override
            public void run() {
                // We use MATCH_UNINSTALLED_PACKAGES as the app can be on SD card as well.
                int uninstalled = android.os.Build.VERSION.SDK_INT >= 24 ? PackageManager.MATCH_UNINSTALLED_PACKAGES : PackageManager.GET_UNINSTALLED_PACKAGES;

                boolean uninstallSuccessful = LauncherAppsCompat.getInstance(launcher)
                        .getApplicationInfo(cn.getPackageName(),
                                uninstalled, user) == null;
                callback.onDragObjectRemoved(uninstallSuccessful);
            }
        };
        launcher.addOnResumeCallback(checkIfUninstallWasSuccess);
    } else {
        callback.onDragObjectRemoved(false);
    }
}
 
Example 3
Source File: WidgetPreviewLoader.java    From LaunchEnr with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @return an array of containing versionCode and lastUpdatedTime for the package.
 */
@Thunk private long[] getPackageVersion(String packageName) {
    synchronized (mPackageVersions) {
        long[] versions = mPackageVersions.get(packageName);
        if (versions == null) {
            versions = new long[2];
            try {

                int uninstalled = android.os.Build.VERSION.SDK_INT >= 24 ? PackageManager.MATCH_UNINSTALLED_PACKAGES : PackageManager.GET_UNINSTALLED_PACKAGES;

                PackageInfo info = mContext.getPackageManager().getPackageInfo(packageName, uninstalled);
                versions[0] = info.versionCode;
                versions[1] = info.lastUpdateTime;
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
            mPackageVersions.put(packageName, versions);
        }
        return versions;
    }
}
 
Example 4
Source File: IconCache.java    From LaunchEnr with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Updates the entries related to the given package in memory and persistent DB.
 */
public synchronized void updateIconsForPkg(String packageName, UserHandle user) {
    removeIconsForPkg(packageName, user);
    try {
        int uninstalled = android.os.Build.VERSION.SDK_INT >= 24 ? PackageManager.MATCH_UNINSTALLED_PACKAGES : PackageManager.GET_UNINSTALLED_PACKAGES;

        PackageInfo info = mPackageManager.getPackageInfo(packageName,
                uninstalled);
        long userSerial = mUserManager.getSerialNumberForUser(user);
        for (LauncherActivityInfo app : mLauncherApps.getActivityList(packageName, user)) {
            addIconToDBAndMemCache(app, info, userSerial, false /*replace existing*/);
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
        return;
    }
}
 
Example 5
Source File: DevicePluginInfoFragment.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Tests whether packageName exists in application list.
 *
 * @param packageName package name
 * @return true if packageName exists, false otherwise
 */
private boolean existApplicationFromPackageName(final String packageName) {
    if (packageName == null) {
        return false;
    }

    final PackageManager pm = getActivity().getPackageManager();
    final int flags = PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS;
    final List<ApplicationInfo> installedAppList = pm.getInstalledApplications(flags);
    for (ApplicationInfo app : installedAppList) {
        if (app.packageName.equals(packageName)) {
            return true;
        }
    }
    return false;
}
 
Example 6
Source File: StatusFragment.java    From enterprise-samples with Apache License 2.0 5 votes vote down vote up
private void updateUi(Activity activity) {
    PackageManager packageManager = activity.getPackageManager();
    try {
        int packageFlags;
        if (Build.VERSION.SDK_INT < 24) {
            //noinspection deprecation
            packageFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
        } else {
            packageFlags = PackageManager.MATCH_UNINSTALLED_PACKAGES;
        }
        ApplicationInfo info = packageManager.getApplicationInfo(
                Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA,
                packageFlags);
        DevicePolicyManager devicePolicyManager =
                (DevicePolicyManager) activity.getSystemService(Activity.DEVICE_POLICY_SERVICE);
        if ((info.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
            if (!devicePolicyManager.isApplicationHidden(
                    EnforcerDeviceAdminReceiver.getComponentName(activity),
                    Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA)) {
                // The app is ready to enforce restrictions
                // This is unlikely to happen in this sample as unhideApp() handles it.
                mListener.onStatusUpdated();
            } else {
                // The app is installed but hidden in this profile
                mTextStatus.setText(R.string.status_not_activated);
                mButtonUnhide.setVisibility(View.VISIBLE);
            }
        } else {
            // Need to reinstall the sample app
            mTextStatus.setText(R.string.status_need_reinstall);
            mButtonUnhide.setVisibility(View.GONE);
        }
    } catch (PackageManager.NameNotFoundException e) {
        // Need to reinstall the sample app
        mTextStatus.setText(R.string.status_need_reinstall);
        mButtonUnhide.setVisibility(View.GONE);
    }
}
 
Example 7
Source File: BasicManagedProfileFragment.java    From android-BasicManagedProfile with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the application is available in this profile.
 *
 * @param packageName The package name
 * @return True if the application is available in this profile.
 */
private boolean isApplicationEnabled(String packageName) {
    Activity activity = getActivity();
    PackageManager packageManager = activity.getPackageManager();
    try {
        int packageFlags;
        if(Build.VERSION.SDK_INT < 24){
            //noinspection deprecation
            packageFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
        }else{
            packageFlags = PackageManager.MATCH_UNINSTALLED_PACKAGES;
        }
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(
                packageName, packageFlags);
        // Return false if the app is not installed in this profile
        if (0 == (applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED)) {
            return false;
        }
        // Check if the app is not hidden in this profile
        DevicePolicyManager devicePolicyManager =
                (DevicePolicyManager) activity.getSystemService(Activity.DEVICE_POLICY_SERVICE);
        return !devicePolicyManager.isApplicationHidden(
                BasicDeviceAdminReceiver.getComponentName(activity), packageName);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}
 
Example 8
Source File: StatusFragment.java    From android-AppRestrictionEnforcer with Apache License 2.0 5 votes vote down vote up
private void updateUi(Activity activity) {
    PackageManager packageManager = activity.getPackageManager();
    try {
        int packageFlags;
        if (Build.VERSION.SDK_INT < 24) {
            //noinspection deprecation
            packageFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
        } else {
            packageFlags = PackageManager.MATCH_UNINSTALLED_PACKAGES;
        }
        ApplicationInfo info = packageManager.getApplicationInfo(
                Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA,
                packageFlags);
        DevicePolicyManager devicePolicyManager =
                (DevicePolicyManager) activity.getSystemService(Activity.DEVICE_POLICY_SERVICE);
        if ((info.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
            if (!devicePolicyManager.isApplicationHidden(
                    EnforcerDeviceAdminReceiver.getComponentName(activity),
                    Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA)) {
                // The app is ready to enforce restrictions
                // This is unlikely to happen in this sample as unhideApp() handles it.
                mListener.onStatusUpdated();
            } else {
                // The app is installed but hidden in this profile
                mTextStatus.setText(R.string.status_not_activated);
                mButtonUnhide.setVisibility(View.VISIBLE);
            }
        } else {
            // Need to reinstall the sample app
            mTextStatus.setText(R.string.status_need_reinstall);
            mButtonUnhide.setVisibility(View.GONE);
        }
    } catch (PackageManager.NameNotFoundException e) {
        // Need to reinstall the sample app
        mTextStatus.setText(R.string.status_need_reinstall);
        mButtonUnhide.setVisibility(View.GONE);
    }
}
 
Example 9
Source File: ApplicationManager.java    From product-emm with Apache License 2.0 5 votes vote down vote up
/**
 * Return the list of the package names of the apps(hidden and visible) that are user owned
 *
 * @return - list of package names of the apps that are not system apps
 */
public List<String> getAppsOfUser() {
    List<String> packagesInstalledByUser = new ArrayList<>();
    int flags = PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES
            | PackageManager.GET_UNINSTALLED_PACKAGES;
    List<ApplicationInfo> applications = packageManager.getInstalledApplications(flags);
    for (ApplicationInfo appInfo : applications) {
        if (!((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1)) {
            packagesInstalledByUser.add(appInfo.packageName);
        }
    }
    return packagesInstalledByUser;
}
 
Example 10
Source File: AppInfoArrayAdapter.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
public AppInfoArrayAdapter(Context context, int resource, List<String> pkgNameList,
        boolean includeDisabledApps) {
    super(context, resource, pkgNameList);
    mPackageManager = getContext().getPackageManager();
    if (includeDisabledApps) {
        mAppInfoFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
    }
}
 
Example 11
Source File: ExemptAppDataManager.java    From igniter with GNU General Public License v3.0 5 votes vote down vote up
private List<ApplicationInfo> queryCurrentInstalledApps() {
    int flags = 0;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        flags |= PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS;
    } else { // These flags are deprecated since Nougat.
        flags |= PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS;
    }
    return mPackageManager.getInstalledApplications(flags);
}
 
Example 12
Source File: BasicManagedProfileFragment.java    From enterprise-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the application is available in this profile.
 *
 * @param packageName The package name
 * @return True if the application is available in this profile.
 */
private boolean isApplicationEnabled(String packageName) {
    Activity activity = getActivity();
    PackageManager packageManager = activity.getPackageManager();
    try {
        int packageFlags;
        if(Build.VERSION.SDK_INT < 24){
            //noinspection deprecation
            packageFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
        }else{
            packageFlags = PackageManager.MATCH_UNINSTALLED_PACKAGES;
        }
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(
                packageName, packageFlags);
        // Return false if the app is not installed in this profile
        if (0 == (applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED)) {
            return false;
        }
        // Check if the app is not hidden in this profile
        DevicePolicyManager devicePolicyManager =
                (DevicePolicyManager) activity.getSystemService(Activity.DEVICE_POLICY_SERVICE);
        return !devicePolicyManager.isApplicationHidden(
                BasicDeviceAdminReceiver.getComponentName(activity), packageName);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
}
 
Example 13
Source File: IconCache.java    From Trebuchet with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Gets an entry for the package, which can be used as a fallback entry for various components.
 * This method is not thread safe, it must be called from a synchronized method.
 */
private CacheEntry getEntryForPackageLocked(String packageName, UserHandleCompat user,
        boolean useLowResIcon) {
    ComponentKey cacheKey = getPackageKey(packageName, user);
    CacheEntry entry = mCache.get(cacheKey);

    if (entry == null || (entry.isLowResIcon && !useLowResIcon)) {
        entry = new CacheEntry();
        boolean entryUpdated = true;

        // Check the DB first.
        if (!getEntryFromDB(cacheKey, entry, useLowResIcon)) {
            try {
                int flags = UserHandleCompat.myUserHandle().equals(user) ? 0 :
                    PackageManager.GET_UNINSTALLED_PACKAGES;
                PackageInfo info = mPackageManager.getPackageInfo(packageName, flags);
                ApplicationInfo appInfo = info.applicationInfo;
                if (appInfo == null) {
                    throw new NameNotFoundException("ApplicationInfo is null");
                }
                Drawable drawable = mUserManager.getBadgedDrawableForUser(
                        appInfo.loadIcon(mPackageManager), user);
                entry.icon = Utilities.createIconBitmap(drawable, mContext);
                entry.title = appInfo.loadLabel(mPackageManager);
                entry.contentDescription = mUserManager.getBadgedLabelForUser(entry.title, user);
                entry.isLowResIcon = false;

                // Add the icon in the DB here, since these do not get written during
                // package updates.
                ContentValues values =
                        newContentValues(entry.icon, entry.title.toString(), mPackageBgColor);
                addIconToDB(values, cacheKey.componentName, info,
                        mUserManager.getSerialNumberForUser(user));

            } catch (NameNotFoundException e) {
                if (DEBUG) Log.d(TAG, "Application not installed " + packageName);
                entryUpdated = false;
            }
        }

        // Only add a filled-out entry to the cache
        if (entryUpdated) {
            mCache.put(cacheKey, entry);
        }
    }
    return entry;
}
 
Example 14
Source File: IconCache.java    From LaunchEnr with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Gets an entry for the package, which can be used as a fallback entry for various components.
 * This method is not thread safe, it must be called from a synchronized method.
 */
private CacheEntry getEntryForPackageLocked(String packageName, UserHandle user,
        boolean useLowResIcon) {
    ComponentKey cacheKey = getPackageKey(packageName, user);
    CacheEntry entry = mCache.get(cacheKey);

    if (entry == null || (entry.isLowResIcon && !useLowResIcon)) {
        entry = new CacheEntry();
        boolean entryUpdated = true;

        // Check the DB first.
        if (!getEntryFromDB(cacheKey, entry, useLowResIcon)) {
            try {
                int uninstalled = android.os.Build.VERSION.SDK_INT >= 24 ? PackageManager.MATCH_UNINSTALLED_PACKAGES : PackageManager.GET_UNINSTALLED_PACKAGES;
                int flags = Process.myUserHandle().equals(user) ? 0 : uninstalled;
                PackageInfo info = mPackageManager.getPackageInfo(packageName, flags);
                ApplicationInfo appInfo = info.applicationInfo;
                if (appInfo == null) {
                    throw new NameNotFoundException("ApplicationInfo is null");
                }

                // Load the full res icon for the application, but if useLowResIcon is set, then
                // only keep the low resolution icon instead of the larger full-sized icon
                Bitmap icon = LauncherIcons.createBadgedIconBitmap(
                        appInfo.loadIcon(mPackageManager), user, mContext, appInfo.targetSdkVersion);
                Bitmap lowResIcon =  generateLowResIcon(icon, mPackageBgColor);
                entry.title = appInfo.loadLabel(mPackageManager);
                entry.contentDescription = mUserManager.getBadgedLabelForUser(entry.title, user);
                entry.icon = useLowResIcon ? lowResIcon : icon;
                entry.isLowResIcon = useLowResIcon;

                // Add the icon in the DB here, since these do not get written during
                // package updates.
                ContentValues values =
                        newContentValues(icon, lowResIcon, entry.title.toString(), packageName);
                addIconToDB(values, cacheKey.componentName, info,
                        mUserManager.getSerialNumberForUser(user));

            } catch (NameNotFoundException e) {
                e.printStackTrace();
                entryUpdated = false;
            }
        }

        // Only add a filled-out entry to the cache
        if (entryUpdated) {
            mCache.put(cacheKey, entry);
        }
    }
    return entry;
}
 
Example 15
Source File: AppInfoHelper.java    From PinyinSearchLibrary with Apache License 2.0 4 votes vote down vote up
@SuppressLint("DefaultLocale")
	public List<AppInfo> loadAppInfo(Context context){
		List<AppInfo> appInfos=new ArrayList<AppInfo>();
		List<AppInfo> kanjiStartAppInfos = new ArrayList<AppInfo>();
		List<AppInfo> nonKanjiStartAppInfos = new ArrayList<AppInfo>();
		do{
			if(null==context){
				break;
			}
			
			PackageManager pm=context.getPackageManager();
			
			long startLoadTime=System.currentTimeMillis();
			int flags = PackageManager.GET_UNINSTALLED_PACKAGES;
		
		
			List<PackageInfo> packageInfos=pm.getInstalledPackages(flags);
			Log.i(TAG, packageInfos.size()+"");
			for(PackageInfo pi:packageInfos){
				boolean canLaunchTheMainActivity=AppUtil.appCanLaunchTheMainActivity(mContext, pi.packageName);
				if(true==canLaunchTheMainActivity){
					AppInfo appInfo=getAppInfo(pm, pi);
					if(TextUtils.isEmpty(appInfo.getLabel())){
						continue;
					}
					
					appInfo.getLabelPinyinSearchUnit().setBaseData(appInfo.getLabel());
					PinyinUtil.parse(appInfo.getLabelPinyinSearchUnit());
					String sortKey=PinyinUtil.getSortKey(appInfo.getLabelPinyinSearchUnit()).toUpperCase();
					appInfo.setSortKey(praseSortKey(sortKey));
					boolean isKanji=PinyinUtil.isKanji(appInfo.getLabel().charAt(0));
					if(true==isKanji){
						kanjiStartAppInfos.add(appInfo);
					}else{
						nonKanjiStartAppInfos.add(appInfo);
					}
					
				}
			}
			long endLoadTime=System.currentTimeMillis();
			Log.i(TAG, "endLoadTime-startLoadTime["+(endLoadTime-startLoadTime)+"]");
			//Toast.makeText(mContext, "endLoadTime-startLoadTime["+(endLoadTime-startLoadTime)+"]", Toast.LENGTH_LONG).show();
			break;
		}while(false);
		
		long sortStartTime=System.currentTimeMillis();
		
		Collections.sort(kanjiStartAppInfos, AppInfo.mAscComparator);
		Collections.sort(nonKanjiStartAppInfos, AppInfo.mAscComparator);
		
		//appInfos.addAll(nonKanjiStartAppInfos);
		appInfos.addAll(kanjiStartAppInfos);
	
		/*Start: merge nonKanjiStartAppInfos and kanjiStartAppInfos*/
		int lastIndex=0;
		boolean shouldBeAdd=false;
		for(int i=0; i<nonKanjiStartAppInfos.size(); i++){
			String nonKanfirstLetter=PinyinUtil.getFirstLetter(nonKanjiStartAppInfos.get(i).getLabelPinyinSearchUnit());
			//Log.i(TAG, "nonKanfirstLetter=["+nonKanfirstLetter+"]["+nonKanjiStartAppInfos.get(i).getLabel()+"]["+Integer.valueOf(nonKanjiStartAppInfos.get(i).getLabel().charAt(0))+"]");
			int j=0;
			for(j=0+lastIndex; j<appInfos.size(); j++){
				String firstLetter=PinyinUtil.getFirstLetter(appInfos.get(j).getLabelPinyinSearchUnit());
				lastIndex++;
				if(nonKanfirstLetter.charAt(0)<firstLetter.charAt(0)||nonKanfirstLetter.charAt(0)>THE_LAST_ALPHABET){
					shouldBeAdd=true;
					break;
				}else{
					shouldBeAdd=false;
				}
			}
			
			if(lastIndex>=appInfos.size()){
				lastIndex++;
				shouldBeAdd=true;
				//Log.i(TAG, "lastIndex="+lastIndex);
			}
			
			if(true==shouldBeAdd){
				appInfos.add(j, nonKanjiStartAppInfos.get(i));
				shouldBeAdd=false;
			}
		}
		/*End: merge nonKanjiStartAppInfos and kanjiStartAppInfos*/
	
		
/*		for(int i=0; i<appInfos.size(); i++){
			Log.i(TAG, i+"["+appInfos.get(i).getLabel()+"]");
		}*/
		
		long sortEndTime=System.currentTimeMillis();
		Log.i(TAG, "sortEndTime-sortStartTime["+(sortEndTime-sortStartTime)+"]");
	
		Log.i(TAG, "appInfos.size()"+ appInfos.size());
		//Toast.makeText(context,"["+ appInfos.get(0).getLabel()+"]["+appInfos.get(0).getPackageName()+"]", Toast.LENGTH_LONG).show();
		return appInfos;
	}
 
Example 16
Source File: MainActivity.java    From android-AppRestrictionEnforcer with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_real);
    if (null == savedInstanceState) {
        DevicePolicyManager devicePolicyManager =
                (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        PackageManager packageManager = getPackageManager();
        if (!devicePolicyManager.isProfileOwnerApp(getApplicationContext().getPackageName())) {
            // If the managed profile is not yet set up, we show the setup screen.
            showSetupProfile();
        } else {
            try {
                int packageFlags;
                if (Build.VERSION.SDK_INT < 24) {
                    //noinspection deprecation
                    packageFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
                } else {
                    packageFlags = PackageManager.MATCH_UNINSTALLED_PACKAGES;
                }
                ApplicationInfo info = packageManager.getApplicationInfo(
                        Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA,
                        packageFlags);
                if (0 == (info.flags & ApplicationInfo.FLAG_INSTALLED)) {
                    // Need to reinstall the sample app
                    showStatusProfile();
                } else if (devicePolicyManager.isApplicationHidden(
                        EnforcerDeviceAdminReceiver.getComponentName(this),
                        Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA)) {
                    // The app is installed but hidden in this profile
                    showStatusProfile();
                } else {
                    // Everything is clear; show the main screen
                    showMainFragment();
                }
            } catch (PackageManager.NameNotFoundException e) {
                showStatusProfile();
            }
        }
    }
}
 
Example 17
Source File: MainActivity.java    From enterprise-samples with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (null == savedInstanceState) {
        DevicePolicyManager devicePolicyManager =
                (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        PackageManager packageManager = getPackageManager();
        if (!devicePolicyManager.isProfileOwnerApp(getApplicationContext().getPackageName())) {
            // If the managed profile is not yet set up, we show the setup screen.
            showSetupProfile();
        } else {
            try {
                int packageFlags;
                if (Build.VERSION.SDK_INT < 24) {
                    //noinspection deprecation
                    packageFlags = PackageManager.GET_UNINSTALLED_PACKAGES;
                } else {
                    packageFlags = PackageManager.MATCH_UNINSTALLED_PACKAGES;
                }
                ApplicationInfo info = packageManager.getApplicationInfo(
                        Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA,
                        packageFlags);
                if (0 == (info.flags & ApplicationInfo.FLAG_INSTALLED)) {
                    // Need to reinstall the sample app
                    showStatusProfile();
                } else if (devicePolicyManager.isApplicationHidden(
                        EnforcerDeviceAdminReceiver.getComponentName(this),
                        Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA)) {
                    // The app is installed but hidden in this profile
                    showStatusProfile();
                } else {
                    // Everything is clear; show the main screen
                    showMainFragment();
                }
            } catch (PackageManager.NameNotFoundException e) {
                showStatusProfile();
            }
        }
    }
}