android.content.pm.LauncherApps Java Examples

The following examples show how to use android.content.pm.LauncherApps. 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: ShortcutRequestPinProcessor.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Handle {@link android.content.pm.ShortcutManager#createShortcutResultIntent(ShortcutInfo)}.
 * In this flow the PinItemRequest is delivered to the caller app. Its the app's responsibility
 * to send it to the Launcher app (via {@link android.app.Activity#setResult(int, Intent)}).
 */
public Intent createShortcutResultIntent(@NonNull ShortcutInfo inShortcut, int userId) {
    // Find the default launcher activity
    final int launcherUserId = mService.getParentOrSelfUserId(userId);
    final ComponentName defaultLauncher = mService.getDefaultLauncher(launcherUserId);
    if (defaultLauncher == null) {
        Log.e(TAG, "Default launcher not found.");
        return null;
    }

    // Make sure the launcher user is unlocked. (it's always the parent profile, so should
    // really be unlocked here though.)
    mService.throwIfUserLockedL(launcherUserId);

    // Next, validate the incoming shortcut, etc.
    final PinItemRequest request = requestPinShortcutLocked(inShortcut, null,
            Pair.create(defaultLauncher, launcherUserId));
    return new Intent().putExtra(LauncherApps.EXTRA_PIN_ITEM_REQUEST, request);
}
 
Example #2
Source File: ShortcutRequestPinProcessor.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private boolean startRequestConfirmActivity(ComponentName activity, int launcherUserId,
        PinItemRequest request, int requestType) {
    final String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
            LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
            LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;

    // Start the activity.
    final Intent confirmIntent = new Intent(action);
    confirmIntent.setComponent(activity);
    confirmIntent.putExtra(LauncherApps.EXTRA_PIN_ITEM_REQUEST, request);
    confirmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    final long token = mService.injectClearCallingIdentity();
    try {
        mService.mContext.startActivityAsUser(
                confirmIntent, UserHandle.of(launcherUserId));
    } catch (RuntimeException e) { // ActivityNotFoundException, etc.
        Log.e(TAG, "Unable to start activity " + activity, e);
        return false;
    } finally {
        mService.injectRestoreCallingIdentity(token);
    }
    return true;
}
 
Example #3
Source File: ShortcutService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Get the {@link LauncherApps#ACTION_CONFIRM_PIN_SHORTCUT} or
 * {@link LauncherApps#ACTION_CONFIRM_PIN_APPWIDGET} activity in a given package depending on
 * the requestType.
 */
@Nullable
ComponentName injectGetPinConfirmationActivity(@NonNull String launcherPackageName,
        int launcherUserId, int requestType) {
    Preconditions.checkNotNull(launcherPackageName);
    String action = requestType == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT ?
            LauncherApps.ACTION_CONFIRM_PIN_SHORTCUT :
            LauncherApps.ACTION_CONFIRM_PIN_APPWIDGET;

    final Intent confirmIntent = new Intent(action).setPackage(launcherPackageName);
    final List<ResolveInfo> candidates = queryActivities(
            confirmIntent, launcherUserId, /* exportedOnly =*/ false);
    for (ResolveInfo ri : candidates) {
        return ri.activityInfo.getComponentName();
    }
    return null;
}
 
Example #4
Source File: HomeActivityDelegate.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
@Override
protected void onDestroy() {
    super.onDestroy();

    U.unregisterReceiver(this, killReceiver);
    U.unregisterReceiver(this, forceTaskbarStartReceiver);
    U.unregisterReceiver(this, freeformToggleReceiver);

    if(isSecondaryHome)
        U.unregisterReceiver(this, restartReceiver);

    if(isWallpaperEnabled) {
        U.unregisterReceiver(this, removeDesktopWallpaperReceiver);
        U.unregisterReceiver(this, wallpaperChangeRequestReceiver);
    }

    if(isDesktopIconsEnabled) {
        U.unregisterReceiver(this, refreshDesktopIconsReceiver);
        U.unregisterReceiver(this, iconArrangeModeReceiver);
        U.unregisterReceiver(this, sortDesktopIconsReceiver);
        U.unregisterReceiver(this, updateMarginsReceiver);

        LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);
        launcherApps.unregisterCallback(callback);
    }
}
 
Example #5
Source File: AppUtils.java    From HgLauncher with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fetch and return shortcuts for a specific app.
 *
 * @param launcherApps  LauncherApps service from an activity.
 * @param componentName The component name to flatten to package name.
 *
 * @return A list of shortcut. Null if nonexistent.
 */
@TargetApi(Build.VERSION_CODES.N_MR1)
public static List<ShortcutInfo> getShortcuts(LauncherApps launcherApps, String componentName) {
    // Return nothing if we don't have permission to retrieve shortcuts.
    if (launcherApps == null || !launcherApps.hasShortcutHostPermission()) {
        return new ArrayList<>(0);
    }

    LauncherApps.ShortcutQuery shortcutQuery = new LauncherApps.ShortcutQuery();
    shortcutQuery.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC
            | LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST
            | LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED);
    shortcutQuery.setPackage(getPackageName(componentName));

    return launcherApps.getShortcuts(shortcutQuery, Process.myUserHandle());
}
 
Example #6
Source File: IslandProvisioning.java    From island with Apache License 2.0 6 votes vote down vote up
@ProfileUser private static boolean launchMainActivityInOwnerUser(final Context context) {
	final LauncherApps apps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
	if (apps == null) return false;
	final ComponentName activity = Modules.getMainLaunchActivity(context);
	if (apps.isActivityEnabled(activity, Users.owner)) {
		apps.startMainActivity(activity, Users.owner, null, null);
		return true;
	}
	// Since Android O, activities in owner user is invisible to managed profile, use special forward rule to launch it in owner user.
	new DevicePolicies(context).execute(DevicePolicyManager::addCrossProfileIntentFilter,
			IntentFilters.forAction(Intent.ACTION_MAIN).withCategory(CATEGORY_MAIN_ACTIVITY), FLAG_PARENT_CAN_ACCESS_MANAGED);
	try {
		context.startActivity(new Intent(Intent.ACTION_MAIN).addCategory(CATEGORY_MAIN_ACTIVITY).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
		return true;
	} catch (final ActivityNotFoundException e) {
		return false;
	}
}
 
Example #7
Source File: TaskbarController.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
int filterRealPinnedApps(Context context,
                         List<AppEntry> pinnedApps,
                         List<AppEntry> entries,
                         List<String> applicationIdsToRemove) {
    int realNumOfPinnedApps = 0;
    if(pinnedApps.size() > 0) {
        UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);

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

            if(packageEnabled)
                entries.add(entry);
            else
                realNumOfPinnedApps--;

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

        realNumOfPinnedApps = realNumOfPinnedApps + pinnedApps.size();
    }
    return realNumOfPinnedApps;
}
 
Example #8
Source File: ShortcutConfigActivityInfo.java    From LaunchEnr with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean startConfigActivity(Activity activity, int requestCode) {
    if (getUser().equals(Process.myUserHandle())) {
        return super.startConfigActivity(activity, requestCode);
    }
    try {
        Method m = LauncherApps.class.getDeclaredMethod(
                "getShortcutConfigActivityIntent", LauncherActivityInfo.class);
        IntentSender is = (IntentSender) m.invoke(
                activity.getSystemService(LauncherApps.class), mInfo);
        activity.startIntentSenderForResult(is, requestCode, null, 0, 0, 0);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example #9
Source File: AppUtils.java    From HgLauncher with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fetch and return shortcuts for a specific app.
 *
 * @param launcherApps  LauncherApps service from an activity.
 * @param componentName The component name to flatten to package name.
 *
 * @return A list of shortcut. Null if nonexistent.
 */
@TargetApi(Build.VERSION_CODES.N_MR1)
public static List<ShortcutInfo> getShortcuts(LauncherApps launcherApps, String componentName) {
    // Return nothing if we don't have permission to retrieve shortcuts.
    if (launcherApps == null || !launcherApps.hasShortcutHostPermission()) {
        return new ArrayList<>(0);
    }

    LauncherApps.ShortcutQuery shortcutQuery = new LauncherApps.ShortcutQuery();
    shortcutQuery.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC
            | LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST
            | LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED);
    shortcutQuery.setPackage(getPackageName(componentName));

    return launcherApps.getShortcuts(shortcutQuery, Process.myUserHandle());
}
 
Example #10
Source File: ActionMenu.java    From LaunchTime with GNU General Public License v3.0 5 votes vote down vote up
private void addShortcutToActionPopup(final LauncherApps launcherApps, final ShortcutInfo shortcutInfo) {
    if (Build.VERSION.SDK_INT>=25) {
        if (shortcutInfo != null && shortcutInfo.getActivity() != null) {
            //Log.d(TAG, shortcutInfo.getShortLabel() + " " + shortcutInfo.getActivity().getClassName());

            if (shortcutInfo.isEnabled()) {

                String label = "";
                if (shortcutInfo.getShortLabel() != null)
                    label += shortcutInfo.getShortLabel();

                if (shortcutInfo.getLongLabel() != null && !label.contentEquals(shortcutInfo.getLongLabel()))
                    label = shortcutInfo.getLongLabel() + "";

                Drawable icon = launcherApps.getShortcutIconDrawable(shortcutInfo, DisplayMetrics.DENSITY_DEFAULT);
                addActionMenuItem(label.trim(), icon, new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= 25) {
                            try {
                                launcherApps.startShortcut(shortcutInfo, null, null);
                            } catch (Exception e) {
                                Log.e(TAG, "Couldn't Launch shortcut", e);
                            }
                        }
                        dismissActionPopup();
                    }
                });

            }
        }
    }
}
 
Example #11
Source File: ShortcutUtil.java    From paper-launcher with MIT License 5 votes vote down vote up
public static Drawable loadDrawable(Context context, ShortcutInfo shortcutInfo) {
    if (!SDKUtil.AT_LEAST_N_MR1) {
        return null;
    }

    return ((LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE))
            .getShortcutIconDrawable(shortcutInfo, context.getResources().getDisplayMetrics().densityDpi);
}
 
Example #12
Source File: IslandSetup.java    From island with Apache License 2.0 5 votes vote down vote up
private static void installIslandInProfileWithRoot(final Activity activity, final ProgressDialog progress) {
	// Disable package verifier before installation, to avoid hanging too long.
	final StringBuilder commands = new StringBuilder();
	final String adb_verify_value_before = Settings.Global.getString(activity.getContentResolver(), PACKAGE_VERIFIER_INCLUDE_ADB);
	if (adb_verify_value_before == null || Integer.parseInt(adb_verify_value_before) != 0)
		commands.append("settings put global ").append(PACKAGE_VERIFIER_INCLUDE_ADB).append(" 0 ; ");

	final ApplicationInfo info; try {
		info = activity.getPackageManager().getApplicationInfo(Modules.MODULE_ENGINE, 0);
	} catch (final NameNotFoundException e) { return; }	// Should never happen.
	final int profile_id = Users.toId(Users.profile);
	commands.append("pm install -r --user ").append(profile_id).append(' ');
	if (BuildConfig.DEBUG) commands.append("-t ");
	commands.append(info.sourceDir).append(" && ");

	if (adb_verify_value_before == null) commands.append("settings delete global ").append(PACKAGE_VERIFIER_INCLUDE_ADB).append(" ; ");
	else commands.append("settings put global ").append(PACKAGE_VERIFIER_INCLUDE_ADB).append(' ').append(adb_verify_value_before).append(" ; ");

	// All following commands must be executed all together with the above one, since this app process will be killed upon "pm install".
	final String flat_admin_component = DeviceAdmins.getComponentName(activity).flattenToString();
	commands.append(SDK_INT >= M ? "dpm set-profile-owner --user " + profile_id + " " + flat_admin_component
			: "dpm set-profile-owner " + flat_admin_component + " " + profile_id);
	commands.append(" && am start-user ").append(profile_id);

	SafeAsyncTask.execute(activity, a -> Shell.SU.run(commands.toString()), result -> {
		final LauncherApps launcher_apps = Objects.requireNonNull((LauncherApps) activity.getSystemService(Context.LAUNCHER_APPS_SERVICE));
		if (launcher_apps.getActivityList(activity.getPackageName(), Users.profile).isEmpty()) {
			Analytics.$().event("setup_island_root_failed").withRaw("command", commands.toString())
					.with(CONTENT, result == null ? "<null>" : stream(result).collect(joining("\n"))).send();
			dismissProgressAndShowError(activity, progress, 2);
		}
	});
}
 
Example #13
Source File: PinShortcutActivity.java    From LaunchTime with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.O)
private void acceptShortcut(LauncherApps launcherApps, LauncherApps.PinItemRequest request) {
    ShortcutReceiver shrecv = GlobState.getShortcutReceiver(this);
    if (shrecv == null) {
        return;
    }

    ShortcutInfo si = request.getShortcutInfo();
    if (si == null) {
        return;
    }
    Drawable iconDrawable = launcherApps.getShortcutIconDrawable(si, 0);

    Bitmap icon = null;

    if (iconDrawable != null) {
        icon = IconsHandler.drawableToBitmap(iconDrawable);
    }

    String label = null;
    if (si.getShortLabel() != null) {
        label = si.getShortLabel().toString();

        CharSequence longlabel = si.getLongLabel();
        if (longlabel != null) {
            if (longlabel.toString().startsWith(label)) {
                label = longlabel.toString();
            } else {
                label += " " + longlabel;
            }
        }


    }

    shrecv.addOreoLink(this, si.getId(), si.getPackage(), label, icon);

    request.accept();
}
 
Example #14
Source File: IslandProvisioning.java    From island with Apache License 2.0 5 votes vote down vote up
private static void disableRedundantPackageInstaller(final Context context, final DevicePolicies policies) {
	final List<ResolveInfo> installers = context.getPackageManager().queryIntentActivities(
			new Intent(Intent.ACTION_INSTALL_PACKAGE).setData(Uri.fromParts("file", "dummy.apk", null)), 0);
	if (installers.size() <= 1) return;
	final LauncherApps launcher_apps = Objects.requireNonNull((LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE));
	for (final ResolveInfo installer : installers) {
		final String installer_pkg = installer.activityInfo.packageName;
		if (launcher_apps.isPackageEnabled(installer_pkg, Users.owner)) continue;
		policies.invoke(DevicePolicyManager::setApplicationHidden, installer_pkg, true);
		Log.i(TAG, "Disabled redundant package installer: " + installer_pkg);
	}
}
 
Example #15
Source File: LauncherIconHelper.java    From HgLauncher with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Loads an icon from the icon pack based on the received package name.
 *
 * @param activity       where LauncherApps service can be retrieved.
 * @param appPackageName Package name of the app whose icon is to be loaded.
 *
 * @return Drawable Will return null if there is no icon associated with the package name,
 * otherwise an associated icon from the icon pack will be returned.
 */
private static Drawable getIconDrawable(Activity activity, String appPackageName, long user) {
    PackageManager packageManager = activity.getPackageManager();
    String componentName = "ComponentInfo{" + appPackageName + "}";
    Resources iconRes = null;
    Drawable defaultIcon = null;

    try {
        if (Utils.atLeastLollipop()) {
            LauncherApps launcher = (LauncherApps) activity.getSystemService(
                    Context.LAUNCHER_APPS_SERVICE);
            UserManager userManager = (UserManager) activity.getSystemService(
                    Context.USER_SERVICE);

            if (userManager != null && launcher != null) {
                defaultIcon = launcher.getActivityList(AppUtils.getPackageName(appPackageName),
                        userManager.getUserForSerialNumber(user))
                                      .get(0).getBadgedIcon(0);
            }
        } else {
            defaultIcon = packageManager.getActivityIcon(
                    ComponentName.unflattenFromString(appPackageName));
        }

        if (!"default".equals(iconPackageName)) {
            iconRes = packageManager.getResourcesForApplication(iconPackageName);
        } else {
            return defaultIcon;
        }
    } catch (PackageManager.NameNotFoundException e) {
        Utils.sendLog(Utils.LogLevel.ERROR, e.toString());
    }

    String drawable = mPackagesDrawables.get(componentName);
    if (drawable != null && iconRes != null) {
        return loadDrawable(iconRes, drawable, iconPackageName);
    } else {
        return defaultIcon;
    }
}
 
Example #16
Source File: FavoriteAppTileService.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
private void updateState() {
    Tile tile = getQsTile();
    if(tile == null) return;

    SharedPreferences pref = U.getSharedPreferences(this);
    if(pref.getBoolean(prefix + "added", false)) {
        tile.setState(Tile.STATE_ACTIVE);
        tile.setLabel(pref.getString(prefix + "label", getString(R.string.tb_new_shortcut)));

        String componentName = pref.getString(prefix + "component_name", null);
        float threshold = pref.getFloat(prefix + "icon_threshold", -1);

        if(componentName != null && threshold >= 0) {
            UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
            LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);
            long userId = pref.getLong(prefix + "user_id", userManager.getSerialNumberForUser(Process.myUserHandle()));

            Intent intent = new Intent();
            intent.setComponent(ComponentName.unflattenFromString(componentName));
            LauncherActivityInfo info = launcherApps.resolveActivity(intent, userManager.getUserForSerialNumber(userId));

            IconCache cache = IconCache.getInstance(this);
            BitmapDrawable icon = U.convertToMonochrome(this, cache.getIcon(this, info), threshold);

            tile.setIcon(Icon.createWithBitmap(icon.getBitmap()));
        } else
            tile.setIcon(Icon.createWithResource(this, R.drawable.tb_favorite_app_tile));
    } else {
        tile.setState(Tile.STATE_INACTIVE);
        tile.setLabel(getString(R.string.tb_new_shortcut));
        tile.setIcon(Icon.createWithResource(this, R.drawable.tb_favorite_app_tile));
    }

    tile.updateTile();
}
 
Example #17
Source File: IslandManager.java    From island with Apache License 2.0 5 votes vote down vote up
@OwnerUser public static boolean launchApp(final Context context, final String pkg, final UserHandle profile) {
	final LauncherApps launcher_apps = Objects.requireNonNull((LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE));
	final List<LauncherActivityInfo> activities = launcher_apps.getActivityList(pkg, profile);
	if (activities == null || activities.isEmpty()) return false;
	launcher_apps.startMainActivity(activities.get(0).getComponentName(), profile, null, null);
	return true;
}
 
Example #18
Source File: ContextMenuActivity.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.N_MR1)
private int getLauncherShortcuts() {
    LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);
    if(launcherApps.hasShortcutHostPermission()) {
        UserManager userManager = (UserManager) getSystemService(USER_SERVICE);

        LauncherApps.ShortcutQuery query = new LauncherApps.ShortcutQuery();
        query.setActivity(ComponentName.unflattenFromString(entry.getComponentName()));
        query.setQueryFlags(LauncherApps.ShortcutQuery.FLAG_MATCH_DYNAMIC
                | LauncherApps.ShortcutQuery.FLAG_MATCH_MANIFEST
                | LauncherApps.ShortcutQuery.FLAG_MATCH_PINNED);

        shortcuts = launcherApps.getShortcuts(query, userManager.getUserForSerialNumber(entry.getUserId(this)));
        if(shortcuts != null)
            return shortcuts.size();
    }

    return 0;
}
 
Example #19
Source File: ShortcutUtil.java    From paper-launcher with MIT License 5 votes vote down vote up
public static void launchShortcut(View view, ShortcutInfo shortcutInfo) {
    if (!SDKUtil.AT_LEAST_N_MR1) {
        return;
    }

    ((LauncherApps) view.getContext().getSystemService(Context.LAUNCHER_APPS_SERVICE))
            .startShortcut(shortcutInfo, IntentUtil.getViewBounds(view), new Bundle());
}
 
Example #20
Source File: ShortcutsLoader.java    From paper-launcher with MIT License 5 votes vote down vote up
@SuppressLint("WrongConstant")
public static List<ShortcutInfo> loadShortcuts(Context context, String packageName) {
    if (!SDKUtil.AT_LEAST_N_MR1) {
        return null;
    }

    LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);
    if (launcherApps == null) {
        return null;
    }

    if (!launcherApps.hasShortcutHostPermission()) {
        return null;
    }

    PackageManager packageManager = context.getPackageManager();
    Intent mainIntent = new Intent("android.intent.action.MAIN", null);
    mainIntent.addCategory("android.intent.category.LAUNCHER");

    if (packageManager != null && packageManager.queryIntentActivities(mainIntent, 0) != null) {
        try {
            return launcherApps.getShortcuts((new LauncherApps.ShortcutQuery())
                            .setPackage(packageName).setQueryFlags(QUERY_FLAGS),
                    UserHandle.getUserHandleForUid(context.getPackageManager().getPackageUid(packageName, PackageManager.GET_META_DATA)));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();

            return null;
        }
    }

    return null;
}
 
Example #21
Source File: AppListViewModel.java    From island with Apache License 2.0 5 votes vote down vote up
private static void launchSystemAppSettings(final Context context, final IslandAppInfo app) {
	// Stock app info activity requires the target app not hidden.
	unfreezeIfNeeded(context, app).thenAccept(unfrozen -> {
		if (unfrozen) requireNonNull((LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE))
				.startAppDetailsActivity(new ComponentName(app.packageName, ""), app.user, null, null);
	});
}
 
Example #22
Source File: MainActivity.java    From island with Apache License 2.0 5 votes vote down vote up
@Override protected void onCreate(final Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	if (Users.isProfile()) {	// Should generally not run in profile, unless the managed profile provision is interrupted or manually provision is not complete.
		onCreateInProfile();
		finish();
		return;
	}
	if (mIsDeviceOwner = new DevicePolicies(this).isActiveDeviceOwner()) {
		startMainUi(savedInstanceState);	// As device owner, always show main UI.
		return;
	}
	final UserHandle profile = Users.profile;
	if (profile == null) {					// Nothing setup yet
		startSetupWizard();
		return;
	}

	final Optional<Boolean> is_profile_owner = DevicePolicies.isProfileOwner(this, profile);
	if (is_profile_owner == null) { 	// Profile owner cannot be detected, the best bet is to continue to the main UI.
		startMainUi(savedInstanceState);
	} else if (! is_profile_owner.isPresent()) {	// Profile without owner, probably caused by provisioning interrupted before device-admin is activated.
		if (IslandManager.launchApp(this, getPackageName(), profile)) finish();	// Try starting Island in profile to finish the provisioning.
		else startSetupWizard();		// Cannot resume the provisioning, probably this profile is not created by us, go ahead with normal setup.
	} else if (! is_profile_owner.get()) {			// Profile is not owned by us, show setup wizard.
		startSetupWizard();
	} else {
		final LauncherApps launcher_apps = (LauncherApps) getSystemService(Context.LAUNCHER_APPS_SERVICE);
		final List<LauncherActivityInfo> our_activities_in_launcher;
		if (launcher_apps != null && ! (our_activities_in_launcher = launcher_apps.getActivityList(getPackageName(), profile)).isEmpty()) {
			// Main activity is left enabled, probably due to pending post-provisioning in manual setup. Some domestic ROMs may block implicit broadcast, causing ACTION_USER_INITIALIZE being dropped.
			Analytics.$().event("profile_provision_leftover").send();
			Log.w(TAG, "Setup in Island is not complete, continue it now.");
			launcher_apps.startMainActivity(our_activities_in_launcher.get(0).getComponentName(), profile, null, null);
			finish();
			return;
		}
		startMainUi(savedInstanceState);
	}
}
 
Example #23
Source File: LauncherAppsCompatVO.java    From LaunchEnr with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<ShortcutConfigActivityInfo> getCustomShortcutActivityList(
        @Nullable PackageUserKey packageUser) {
    List<ShortcutConfigActivityInfo> result = new ArrayList<>();
    UserHandle myUser = Process.myUserHandle();

    try {
        Method m = LauncherApps.class.getDeclaredMethod("getShortcutConfigActivityList",
                String.class, UserHandle.class);
        final List<UserHandle> users;
        final String packageName;
        if (packageUser == null) {
            users = UserManagerCompat.getInstance(mContext).getUserProfiles();
            packageName = null;
        } else {
            users = new ArrayList<>(1);
            users.add(packageUser.mUser);
            packageName = packageUser.mPackageName;
        }
        for (UserHandle user : users) {
            boolean ignoreTargetSdk = myUser.equals(user);
            List<LauncherActivityInfo> activities =
                    (List<LauncherActivityInfo>) m.invoke(mLauncherApps, packageName, user);
            for (LauncherActivityInfo activityInfo : activities) {
                if (ignoreTargetSdk || activityInfo.getApplicationInfo().targetSdkVersion >=
                        Build.VERSION_CODES.O) {
                    result.add(new ShortcutConfigActivityInfoVO(activityInfo));
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}
 
Example #24
Source File: U.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
private static void launchAndroidForWork(Context context, ComponentName componentName, Bundle bundle, long userId, Runnable onError) {
    UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
    LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);

    try {
        launcherApps.startMainActivity(componentName, userManager.getUserForSerialNumber(userId), null, bundle);
    } catch (ActivityNotFoundException | NullPointerException
            | IllegalStateException | SecurityException e) {
        if(onError != null) launchApp(context, onError);
    }
}
 
Example #25
Source File: U.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.N_MR1)
private static void launchShortcut(Context context, ShortcutInfo shortcut, Bundle bundle, Runnable onError) {
    LauncherApps launcherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE);

    if(launcherApps.hasShortcutHostPermission()) {
        try {
            launcherApps.startShortcut(shortcut, null, bundle);
        } catch (ActivityNotFoundException | NullPointerException
                | IllegalStateException | SecurityException e) {
            if(onError != null) launchApp(context, onError);
        }
    }
}
 
Example #26
Source File: LauncherAppsCompat.java    From deagle with Apache License 2.0 5 votes vote down vote up
@RequiresApi(N) @SuppressLint("NewApi")
public static ApplicationInfo getApplicationInfoNoThrows(final LauncherApps la, final String pkg, final int flags, final UserHandle user) {
	try {
		return la.getApplicationInfo(pkg, flags, user);
	} catch (final PackageManager.NameNotFoundException e) {
		return null;
	}
}
 
Example #27
Source File: LauncherIconHelper.java    From HgLauncher with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Loads an icon from the icon pack based on the received package name.
 *
 * @param activity       where LauncherApps service can be retrieved.
 * @param appPackageName Package name of the app whose icon is to be loaded.
 *
 * @return Drawable Will return null if there is no icon associated with the package name,
 * otherwise an associated icon from the icon pack will be returned.
 */
private static Drawable getIconDrawable(Activity activity, String appPackageName, long user) {
    PackageManager packageManager = activity.getPackageManager();
    String componentName = "ComponentInfo{" + appPackageName + "}";
    Resources iconRes = null;
    Drawable defaultIcon = null;

    try {
        if (Utils.atLeastLollipop()) {
            LauncherApps launcher = (LauncherApps) activity.getSystemService(
                    Context.LAUNCHER_APPS_SERVICE);
            UserManager userManager = (UserManager) activity.getSystemService(
                    Context.USER_SERVICE);

            if (userManager != null && launcher != null) {
                defaultIcon = launcher.getActivityList(AppUtils.getPackageName(appPackageName),
                        userManager.getUserForSerialNumber(user))
                                      .get(0).getBadgedIcon(0);
            }
        } else {
            defaultIcon = packageManager.getActivityIcon(
                    ComponentName.unflattenFromString(appPackageName));
        }

        if (!"default".equals(iconPackageName)) {
            iconRes = packageManager.getResourcesForApplication(iconPackageName);
        } else {
            return defaultIcon;
        }
    } catch (PackageManager.NameNotFoundException e) {
        Utils.sendLog(Utils.LogLevel.ERROR, e.toString());
    }

    String drawable = mPackagesDrawables.get(componentName);
    if (drawable != null && iconRes != null) {
        return loadDrawable(iconRes, drawable, iconPackageName);
    } else {
        return defaultIcon;
    }
}
 
Example #28
Source File: IslandAppInfo.java    From island with Apache License 2.0 4 votes vote down vote up
public boolean isHidden() {
	final Boolean hidden = isHidden(this);
	if (hidden != null) return hidden;
	// The fallback implementation
	return ! Objects.requireNonNull((LauncherApps) context().getSystemService(LAUNCHER_APPS_SERVICE)).isPackageEnabled(packageName, myUserHandle());
}
 
Example #29
Source File: LauncherAppsCompat.java    From deagle with Apache License 2.0 4 votes vote down vote up
public final LauncherApps get() {
	return mLauncherApps;
}
 
Example #30
Source File: LauncherAppsCompatVL.java    From Trebuchet with GNU General Public License v3.0 4 votes vote down vote up
LauncherAppsCompatVL(Context context) {
    super();
    mLauncherApps = (LauncherApps) context.getSystemService("launcherapps");
}