Java Code Examples for android.content.ComponentName#unflattenFromString()

The following examples show how to use android.content.ComponentName#unflattenFromString() . 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: ComponentKey.java    From Trebuchet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new component key from an encoded component key string in the form of
 * [flattenedComponentString#userId].  If the userId is not present, then it defaults
 * to the current user.
 */
public ComponentKey(Context context, String componentKeyStr) {
    int userDelimiterIndex = componentKeyStr.indexOf("#");
    if (userDelimiterIndex != -1) {
        String componentStr = componentKeyStr.substring(0, userDelimiterIndex);
        Long componentUser = Long.valueOf(componentKeyStr.substring(userDelimiterIndex + 1));
        componentName = ComponentName.unflattenFromString(componentStr);
        user = UserManagerCompat.getInstance(context)
                .getUserForSerialNumber(componentUser.longValue());
    } else {
        // No user provided, default to the current user
        componentName = ComponentName.unflattenFromString(componentKeyStr);
        user = UserHandleCompat.myUserHandle();
    }
    mHashCode = Arrays.hashCode(new Object[] {componentName, user});
}
 
Example 2
Source File: NotificationsPlugin.java    From flutter-plugins with MIT License 6 votes vote down vote up
/**
 * For all enabled notification listeners, check if any of them matches the package name of this application.
 * If any match is found, return true. Otherwise if no matches were found, return false.
 */
private boolean permissionGiven() {
    String packageName = context.getPackageName();
    String flat = Settings.Secure.getString(context.getContentResolver(),
            ENABLED_NOTIFICATION_LISTENERS);
    if (!TextUtils.isEmpty(flat)) {
        String[] names = flat.split(":");
        for (String name : names) {
            ComponentName componentName = ComponentName.unflattenFromString(name);
            boolean nameMatch = TextUtils.equals(packageName, componentName.getPackageName());
            if (nameMatch) {
                return true;
            }
        }
    }
    return false;
}
 
Example 3
Source File: IntentFirewall.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
protected void readChild(XmlPullParser parser) throws IOException, XmlPullParserException {
    String currentTag = parser.getName();

    if (currentTag.equals(TAG_INTENT_FILTER)) {
        FirewallIntentFilter intentFilter = new FirewallIntentFilter(this);
        intentFilter.readFromXml(parser);
        mIntentFilters.add(intentFilter);
    } else if (currentTag.equals(TAG_COMPONENT_FILTER)) {
        String componentStr = parser.getAttributeValue(null, ATTR_NAME);
        if (componentStr == null) {
            throw new XmlPullParserException("Component name must be specified.",
                    parser, null);
        }

        ComponentName componentName = ComponentName.unflattenFromString(componentStr);
        if (componentName == null) {
            throw new XmlPullParserException("Invalid component name: " + componentStr);
        }

        mComponentFilters.add(componentName);
    } else {
        super.readChild(parser);
    }
}
 
Example 4
Source File: MainActivity.java    From notification-listener-service-example with MIT License 6 votes vote down vote up
/**
 * Is Notification Service Enabled.
 * Verifies if the notification listener service is enabled.
 * Got it from: https://github.com/kpbird/NotificationListenerService-Example/blob/master/NLSExample/src/main/java/com/kpbird/nlsexample/NLService.java
 * @return True if enabled, false otherwise.
 */
private boolean isNotificationServiceEnabled(){
    String pkgName = getPackageName();
    final String flat = Settings.Secure.getString(getContentResolver(),
            ENABLED_NOTIFICATION_LISTENERS);
    if (!TextUtils.isEmpty(flat)) {
        final String[] names = flat.split(":");
        for (int i = 0; i < names.length; i++) {
            final ComponentName cn = ComponentName.unflattenFromString(names[i]);
            if (cn != null) {
                if (TextUtils.equals(pkgName, cn.getPackageName())) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 5
Source File: AppUtils.java    From HgLauncher with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Launches an activity based on its component name.
 *
 * @param activity      Current foreground activity.
 * @param componentName Component name of the app to be launched.
 */
static void quickLaunch(Activity activity, String componentName) throws ActivityNotFoundException {
    // When receiving 'none', it's probably a gesture that hasn't been registered.
    if ("none".equals(componentName)) {
        return;
    }

    ComponentName component = ComponentName.unflattenFromString(componentName);

    // Forcibly end if we can't unflatten the string.
    if (component == null) {
        return;
    }

    Intent intent = Intent.makeMainActivity(component);
    intent.setFlags(
            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

    activity.startActivity(intent);
}
 
Example 6
Source File: EnabledComponentsObserver.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private ArraySet<ComponentName> loadComponentNamesFromSetting(String settingName,
        int userId) {
    final ContentResolver cr = mContext.getContentResolver();
    String settingValue = Settings.Secure.getStringForUser(
            cr,
            settingName,
            userId);
    if (TextUtils.isEmpty(settingValue))
        return new ArraySet<>();
    String[] restored = settingValue.split(ENABLED_SERVICES_SEPARATOR);
    ArraySet<ComponentName> result = new ArraySet<>(restored.length);
    for (int i = 0; i < restored.length; i++) {
        ComponentName value = ComponentName.unflattenFromString(restored[i]);
        if (null != value) {
            result.add(value);
        }
    }
    return result;
}
 
Example 7
Source File: ShortcutService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Nullable
static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
    final String value = parseStringAttribute(parser, attribute);
    if (TextUtils.isEmpty(value)) {
        return null;
    }
    return ComponentName.unflattenFromString(value);
}
 
Example 8
Source File: NotificationService.java    From android-common with Apache License 2.0 5 votes vote down vote up
public static boolean isNotificationListenEnable(Context context, String pkgName) {
    final String flat = Settings.Secure.getString(context.getContentResolver(), ENABLED_NOTIFICATION_LISTENERS);
    if (!TextUtils.isEmpty(flat)) {
        final String[] names = flat.split(":");
        for (int i = 0; i < names.length; i++) {
            final ComponentName cn = ComponentName.unflattenFromString(names[i]);
            if (cn != null) {
                if (TextUtils.equals(pkgName, cn.getPackageName())) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 9
Source File: DreamManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private ComponentName getDozeComponent(int userId) {
    if (mDozeConfig.enabled(userId)) {
        return ComponentName.unflattenFromString(mDozeConfig.ambientDisplayComponent());
    } else {
        return null;
    }

}
 
Example 10
Source File: AppUtils.java    From HgLauncher with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get simple package name from a flattened ComponentName.
 *
 * @param componentName The flattened ComponentName whose package name is to be returned.
 *
 * @return String The package name if not null.
 */
public static String getPackageName(String componentName) {
    ComponentName unflattened = ComponentName.unflattenFromString(componentName);
    if (unflattened != null) {
        return unflattened.getPackageName();
    } else {
        return "";
    }
}
 
Example 11
Source File: VoiceInteractionService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether the given service component is the currently active
 * VoiceInteractionService.
 */
public static boolean isActiveService(Context context, ComponentName service) {
    String cur = Settings.Secure.getString(context.getContentResolver(),
            Settings.Secure.VOICE_INTERACTION_SERVICE);
    if (cur == null || cur.isEmpty()) {
        return false;
    }
    ComponentName curComp = ComponentName.unflattenFromString(cur);
    if (curComp == null) {
        return false;
    }
    return curComp.equals(service);
}
 
Example 12
Source File: PersistentPreferredActivity.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
PersistentPreferredActivity(XmlPullParser parser) throws XmlPullParserException, IOException {
    String shortComponent = parser.getAttributeValue(null, ATTR_NAME);
    mComponent = ComponentName.unflattenFromString(shortComponent);
    if (mComponent == null) {
        PackageManagerService.reportSettingsProblem(Log.WARN,
                "Error in package manager settings: " +
                        "Bad activity name " + shortComponent +
                        " at " + parser.getPositionDescription());
    }
    int outerDepth = parser.getDepth();
    String tagName = parser.getName();
    int type;
    while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
            && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
        tagName = parser.getName();
        if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
            continue;
        } else if (type == XmlPullParser.START_TAG) {
            if (tagName.equals(ATTR_FILTER)) {
                break;
            } else {
                PackageManagerService.reportSettingsProblem(Log.WARN,
                        "Unknown element: " + tagName +
                        " at " + parser.getPositionDescription());
                XmlUtils.skipCurrentTag(parser);
            }
        }
    }
    if (tagName.equals(ATTR_FILTER)) {
        readFromXml(parser);
    } else {
        PackageManagerService.reportSettingsProblem(Log.WARN,
                "Missing element filter at " +
                parser.getPositionDescription());
        XmlUtils.skipCurrentTag(parser);
    }
}
 
Example 13
Source File: DashboardController.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
private void addPlaceholder(int cellId) {
    FrameLayout placeholder = cells.get(cellId).findViewById(R.id.placeholder);
    SharedPreferences pref = U.getSharedPreferences(context);
    String providerName = pref.getString("dashboard_widget_" + cellId + "_provider", "null");

    if(!providerName.equals("null")) {
        ImageView imageView = placeholder.findViewById(R.id.placeholder_image);
        ComponentName componentName = ComponentName.unflattenFromString(providerName);

        List<AppWidgetProviderInfo> providerInfoList = mAppWidgetManager.getInstalledProvidersForProfile(Process.myUserHandle());
        for(AppWidgetProviderInfo info : providerInfoList) {
            if(info.provider.equals(componentName)) {
                Drawable drawable = info.loadPreviewImage(context, -1);
                if(drawable == null) drawable = info.loadIcon(context, -1);

                ColorMatrix matrix = new ColorMatrix();
                matrix.setSaturation(0);

                imageView.setImageDrawable(drawable);
                imageView.setColorFilter(new ColorMatrixColorFilter(matrix));
                break;
            }
        }
    }

    placeholder.setVisibility(View.VISIBLE);
}
 
Example 14
Source File: NotificationService.java    From AndroidBase with Apache License 2.0 5 votes vote down vote up
public static boolean isNotificationListenEnable(Context context, String pkgName) {
    final String flat = Settings.Secure.getString(context.getContentResolver(), ENABLED_NOTIFICATION_LISTENERS);
    if (!TextUtils.isEmpty(flat)) {
        final String[] names = flat.split(":");
        for (int i = 0; i < names.length; i++) {
            final ComponentName cn = ComponentName.unflattenFromString(names[i]);
            if (cn != null) {
                if (TextUtils.equals(pkgName, cn.getPackageName())) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 15
Source File: CommonUtils.java    From NotificationBox with MIT License 5 votes vote down vote up
public static boolean checkNotificationReadPermission(Activity activity) {
    String notiStr = Settings.Secure.getString(activity.getContentResolver(), "enabled_notification_listeners");
    if (notiStr != null && !TextUtils.isEmpty(notiStr)) {
        final String[] names = notiStr.split(":");
        for (String name : names) {
            ComponentName cn = ComponentName.unflattenFromString(name);
            if (cn != null) {
                if (activity.getPackageName().equals(cn.getPackageName())) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 16
Source File: DreamManagerService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private ComponentName getDefaultDreamComponentForUser(int userId) {
    String name = Settings.Secure.getStringForUser(mContext.getContentResolver(),
            Settings.Secure.SCREENSAVER_DEFAULT_COMPONENT,
            userId);
    return name == null ? null : ComponentName.unflattenFromString(name);
}
 
Example 17
Source File: PreferredComponent.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public PreferredComponent(Callbacks callbacks, XmlPullParser parser)
        throws XmlPullParserException, IOException {
    mCallbacks = callbacks;
    mShortComponent = parser.getAttributeValue(null, ATTR_NAME);
    mComponent = ComponentName.unflattenFromString(mShortComponent);
    if (mComponent == null) {
        mParseError = "Bad activity name " + mShortComponent;
    }
    String matchStr = parser.getAttributeValue(null, ATTR_MATCH);
    mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
    String setCountStr = parser.getAttributeValue(null, ATTR_SET);
    int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
    String alwaysStr = parser.getAttributeValue(null, ATTR_ALWAYS);
    mAlways = alwaysStr != null ? Boolean.parseBoolean(alwaysStr) : true;

    String[] myPackages = setCount > 0 ? new String[setCount] : null;
    String[] myClasses = setCount > 0 ? new String[setCount] : null;
    String[] myComponents = setCount > 0 ? new String[setCount] : null;

    int setPos = 0;

    int outerDepth = parser.getDepth();
    int type;
    while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
           && (type != XmlPullParser.END_TAG
                   || parser.getDepth() > outerDepth)) {
        if (type == XmlPullParser.END_TAG
                || type == XmlPullParser.TEXT) {
            continue;
        }

        String tagName = parser.getName();
        //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
        //        + parser.getDepth() + " tag=" + tagName);
        if (tagName.equals(TAG_SET)) {
            String name = parser.getAttributeValue(null, ATTR_NAME);
            if (name == null) {
                if (mParseError == null) {
                    mParseError = "No name in set tag in preferred activity "
                        + mShortComponent;
                }
            } else if (setPos >= setCount) {
                if (mParseError == null) {
                    mParseError = "Too many set tags in preferred activity "
                        + mShortComponent;
                }
            } else {
                ComponentName cn = ComponentName.unflattenFromString(name);
                if (cn == null) {
                    if (mParseError == null) {
                        mParseError = "Bad set name " + name + " in preferred activity "
                            + mShortComponent;
                    }
                } else {
                    myPackages[setPos] = cn.getPackageName();
                    myClasses[setPos] = cn.getClassName();
                    myComponents[setPos] = name;
                    setPos++;
                }
            }
            XmlUtils.skipCurrentTag(parser);
        } else if (!mCallbacks.onReadTag(tagName, parser)) {
            Slog.w("PreferredComponent", "Unknown element: " + parser.getName());
            XmlUtils.skipCurrentTag(parser);
        }
    }

    if (setPos != setCount) {
        if (mParseError == null) {
            mParseError = "Not enough set tags (expected " + setCount
                + " but found " + setPos + ") in " + mShortComponent;
        }
    }

    mSetPackages = myPackages;
    mSetClasses = myClasses;
    mSetComponents = myComponents;
}
 
Example 18
Source File: RecognitionServiceManager.java    From AlexaAndroid with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @param str string like {@code ee.ioc.phon.android.speak/.HttpRecognitionService;et-ee}
 * @return ComponentName in the input string
 */
public static ComponentName getComponentName(String str) {
    String[] splits = getServiceAndLang(str);
    return ComponentName.unflattenFromString(splits[0]);
}
 
Example 19
Source File: LaunchModeManager.java    From Phantom with Apache License 2.0 4 votes vote down vote up
/**
 * 获取一个占位activity
 *
 * @param pluginActivity 插件activity
 * @param launchMode     插件activity启动模式
 * @param isFixed        是否建立固定映射关系
 * @return 占位activity
 * @throws ProxyActivityLessException 占位activity不够异常
 */
private String findActivity(String pluginActivity, int launchMode, boolean isFixed)
        throws ProxyActivityLessException {

    String activity = MODE_STANDARD;
    ActivityPool pool = null;

    switch (launchMode) {
        case ActivityInfo.LAUNCH_MULTIPLE:
            final PhantomCore phantomCore = PhantomCore.getInstance();
            final ComponentName componentName = ComponentName.unflattenFromString(pluginActivity);
            if (componentName != null) {
                final ActivityInfo ai = phantomCore.findActivityInfo(componentName);
                final PluginInfo pluginInfo = phantomCore.findPluginInfoByActivityName(componentName);
                final int themeResourceId = ai == null ? -1 : ai.getThemeResource();
                if (themeResourceId != -1 && pluginInfo != null) {
                    final Resources resources = pluginInfo.getPluginResources();
                    if (resources != null) {
                        final Resources.Theme theme = resources.newTheme();
                        theme.applyStyle(themeResourceId, true);
                        final TypedArray sa = theme.obtainStyledAttributes(
                                new int[]{android.R.attr.windowIsTranslucent});
                        final boolean translucent = sa.getBoolean(0, false);
                        sa.recycle();
                        activity = translucent ? MODE_STANDARD_TRANSLUCENT : MODE_STANDARD;
                    }
                }
            }
            break;
        case ActivityInfo.LAUNCH_SINGLE_TOP:
            pool = mSingleTopPool;
            break;
        case ActivityInfo.LAUNCH_SINGLE_INSTANCE:
            pool = mSingleInstancePool;
            break;
        case ActivityInfo.LAUNCH_SINGLE_TASK:
            pool = mSingleTaskPool;
            break;
        default:
            break;
    }

    if (null != pool) {
        activity = isFixed ? pool.resolveFixedActivity(pluginActivity) : pool.resolveActivity(pluginActivity);
    }

    String msg = String.format("resolve %s Activity for %s proxy is %s, fixed is %s",
            launchModeToString(launchMode), pluginActivity, activity, isFixed);
    VLog.d(msg);
    if (null == activity) {
        //占位activity不够使用, 这种情况不做处理,宿主提供足够的占位activity
        //这里不做主动回收,如果做主动回收可能会使程序正常执行流程发送改变
        ProxyActivityLessException pae = new ProxyActivityLessException(msg);
        LogReporter.reportException(pae, null);
        mCache.clean();
        throw pae;
    }

    return activity;
}
 
Example 20
Source File: LauncherBackupHelper.java    From LB-Launcher with Apache License 2.0 4 votes vote down vote up
/**
 * Write all the static widget resources we need to render placeholders
 * for a package that is not installed.
 *
 * @param data output stream for key/value pairs
 * @throws IOException
 */
private void backupWidgets(BackupDataOutput data) throws IOException {
    // persist static widget info that hasn't been persisted yet
    final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
    if (appState == null || !initializeIconCache()) {
        Log.w(TAG, "Failed to get icon cache during restore");
        return;
    }
    final ContentResolver cr = mContext.getContentResolver();
    final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
    final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
    final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
    final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
    if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
    int backupWidgetCount = 0;

    String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
            + getUserSelectionArg();
    Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
            where, null, null);
    try {
        cursor.moveToPosition(-1);
        while(cursor.moveToNext()) {
            final long id = cursor.getLong(ID_INDEX);
            final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
            final int spanX = cursor.getInt(SPANX_INDEX);
            final int spanY = cursor.getInt(SPANY_INDEX);
            final ComponentName provider = ComponentName.unflattenFromString(providerName);
            Key key = null;
            String backupKey = null;
            if (provider != null) {
                key = getKey(Key.WIDGET, providerName);
                backupKey = keyToBackupKey(key);
            } else {
                Log.w(TAG, "empty intent on appwidget: " + id);
            }
            if (mExistingKeys.contains(backupKey)) {
                if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);

                // remember that we already backed this up previously
                mKeys.add(key);
            } else if (backupKey != null) {
                if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
                if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
                    if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
                    previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
                            spanY * profile.cellHeightPx, widgetSpacingLayout);
                    writeRowToBackup(key, packWidget(dpi, previewLoader, mIconCache, provider), data);
                    mKeys.add(key);
                    backupWidgetCount ++;
                } else {
                    if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
                    // too many widgets for this pass, request another.
                    dataChanged();
                }
            }
        }
    } finally {
        cursor.close();
    }
}