Example usage for android.content Intent getComponent

List of usage examples for android.content Intent getComponent

Introduction

In this page you can find the example usage for android.content Intent getComponent.

Prototype

public @Nullable ComponentName getComponent() 

Source Link

Document

Retrieve the concrete component associated with the intent.

Usage

From source file:com.ubikod.capptain.android.sdk.reach.CapptainReachAgent.java

/**
 * Try to notify the content to the user.
 * @param content reach content./*from   ww  w. j  a  v a  2s  . co  m*/
 * @param replaySystemNotifications true iff system notifications must be replayed.
 * @throws RuntimeException if an error occurs.
 */
private void notifyContent(final CapptainReachContent content, boolean replaySystemNotifications)
        throws RuntimeException {
    /* Check expiry */
    final long localId = content.getLocalId();
    if (content.hasExpired()) {
        /* Delete */
        deleteContent(content);
        return;
    }

    /* If datapush, just broadcast, can be done in parallel with another content */
    final Intent intent = content.getIntent();
    if (content instanceof CapptainDataPush) {
        /* If it's a datapush it may already be in the process of broadcasting. */
        if (!mPendingDataPushes.add(localId))
            return;

        /* Broadcast intent */
        final CapptainDataPush dataPush = (CapptainDataPush) content;
        intent.setPackage(mContext.getPackageName());
        mContext.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                /* The last broadcast receiver to set a defined result wins (to determine which result). */
                switch (getResultCode()) {
                case RESULT_OK:
                    dataPush.actionContent(context);
                    break;

                case RESULT_CANCELED:
                    dataPush.exitContent(context);
                    break;

                default:
                    dataPush.dropContent(context);
                }

                /* Clean broadcast state */
                mPendingDataPushes.remove(localId);
            }
        }, null, RESULT_UNDEFINED, null, null);

        /* Datapush processed */
        return;
    }

    /* Don't notify in-app if we are already notifying in app or showing a content */
    if (mState != State.IDLE && !content.isSystemNotification())
        return;

    /* Don't process again a pending notification */
    if (mPendingNotifications.contains(localId))
        return;

    /* Not an interactive content, exit (but there is no other type left, this is just a cast guard) */
    if (!(content instanceof CapptainReachInteractiveContent))
        return;
    CapptainReachInteractiveContent iContent = (CapptainReachInteractiveContent) content;

    /* Don't replay system notification unless told otherwise. */
    if (!replaySystemNotifications && iContent.isSystemNotification()
            && iContent.getNotificationLastDisplayedDate() != null
            && iContent.getNotificationLastDisplayedDate() > mAppLastUpdateTime)
        return;

    /* Check if the content can be notified in the current context (behavior) */
    if (!iContent.canNotify(sActivityManager.getCurrentActivityAlias()))
        return;

    /* If there is a show intent */
    if (intent != null) {
        /* Filter intent for the target package name */
        filterIntent(intent);

        /* If the intent could not be resolved */
        if (intent.getComponent() == null) {
            /* If there was no category */
            if (intent.getCategories() == null)

                /* Notification cannot be done */
                throw new ActivityNotFoundException();

            /* Remove categories */
            Collection<String> categories = new HashSet<String>(intent.getCategories());
            for (String category : categories)
                intent.removeCategory(category);

            /* Try filtering again */
            filterIntent(intent);

            /* Notification cannot be done, skip content */
            if (intent.getComponent() == null)
                throw new ActivityNotFoundException();
        }
    }

    /* Delegate notification */
    Boolean notifierResult = getNotifier(content).handleNotification(iContent);

    /* Check if notifier rejected content notification for now */
    if (Boolean.FALSE.equals(notifierResult))

        /* The notifier rejected the content, nothing more to do */
        return;

    /* Cache content if accepted, it will most likely be used again soon for the next steps. */
    mContentCache.put(localId, content);

    /*
     * If notifier did not return null (e.g. returned true, meaning actually accepted the content),
     * we assume the notification is correctly displayed.
     */
    if (Boolean.TRUE.equals(notifierResult)) {
        /* Report displayed feedback */
        iContent.displayNotification(mContext);

        /* Track in-app content life cycle: one at a time */
        if (!iContent.isSystemNotification())
            mState = State.NOTIFYING_IN_APP;
    }

    /* Track pending notifications to avoid re-processing them every time we change activity. */
    if (notifierResult == null)
        mPendingNotifications.add(localId);
}

From source file:com.android.launcher2.Workspace.java

void updateShortcuts(ArrayList<ApplicationInfo> apps) {
    ArrayList<ShortcutAndWidgetContainer> childrenLayouts = getAllShortcutAndWidgetContainers();
    for (ShortcutAndWidgetContainer layout : childrenLayouts) {
        int childCount = layout.getChildCount();
        for (int j = 0; j < childCount; j++) {
            final View view = layout.getChildAt(j);
            Object tag = view.getTag();
            if (tag instanceof ShortcutInfo) {
                ShortcutInfo info = (ShortcutInfo) tag;
                // We need to check for ACTION_MAIN otherwise getComponent() might
                // return null for some shortcuts (for instance, for shortcuts to
                // web pages.)
                final Intent intent = info.intent;
                final ComponentName name = intent.getComponent();
                if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION
                        && Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) {
                    final int appCount = apps.size();
                    for (int k = 0; k < appCount; k++) {
                        ApplicationInfo app = apps.get(k);
                        if (app.componentName.equals(name)) {
                            BubbleTextView shortcut = (BubbleTextView) view;
                            info.updateIcon(mIconCache);
                            info.title = app.title.toString();
                            shortcut.applyFromShortcutInfo(info, mIconCache);
                        }/*from   w  w  w.  j  a va  2 s.  c  om*/
                    }
                }
            }
        }
    }
}

From source file:com.android.launcher2.Workspace.java

void removeItems(final ArrayList<String> packages) {
    final HashSet<String> packageNames = new HashSet<String>();
    packageNames.addAll(packages);/*  w w w  .j a  va2 s  . c o m*/

    ArrayList<CellLayout> cellLayouts = getWorkspaceAndHotseatCellLayouts();
    for (final CellLayout layoutParent : cellLayouts) {
        final ViewGroup layout = layoutParent.getShortcutsAndWidgets();

        // Avoid ANRs by treating each screen separately
        post(new Runnable() {
            public void run() {
                final ArrayList<View> childrenToRemove = new ArrayList<View>();
                childrenToRemove.clear();

                int childCount = layout.getChildCount();
                for (int j = 0; j < childCount; j++) {
                    final View view = layout.getChildAt(j);
                    Object tag = view.getTag();

                    if (tag instanceof ShortcutInfo) {
                        final ShortcutInfo info = (ShortcutInfo) tag;
                        final Intent intent = info.intent;
                        final ComponentName name = intent.getComponent();

                        if (name != null) {
                            if (packageNames.contains(name.getPackageName())) {
                                LauncherModel.deleteItemFromDatabase(mLauncher, info);
                                childrenToRemove.add(view);
                            }
                        }
                    } else if (tag instanceof FolderInfo) {
                        final FolderInfo info = (FolderInfo) tag;
                        final ArrayList<ShortcutInfo> contents = info.contents;
                        final int contentsCount = contents.size();
                        final ArrayList<ShortcutInfo> appsToRemoveFromFolder = new ArrayList<ShortcutInfo>();

                        for (int k = 0; k < contentsCount; k++) {
                            final ShortcutInfo appInfo = contents.get(k);
                            final Intent intent = appInfo.intent;
                            final ComponentName name = intent.getComponent();

                            if (name != null) {
                                if (packageNames.contains(name.getPackageName())) {
                                    appsToRemoveFromFolder.add(appInfo);
                                }
                            }
                        }
                        for (ShortcutInfo item : appsToRemoveFromFolder) {
                            info.remove(item);
                            LauncherModel.deleteItemFromDatabase(mLauncher, item);
                        }
                    } else if (tag instanceof LauncherAppWidgetInfo) {
                        final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) tag;
                        final ComponentName provider = info.providerName;
                        if (provider != null) {
                            if (packageNames.contains(provider.getPackageName())) {
                                LauncherModel.deleteItemFromDatabase(mLauncher, info);
                                childrenToRemove.add(view);
                            }
                        }
                    }
                }

                childCount = childrenToRemove.size();
                for (int j = 0; j < childCount; j++) {
                    View child = childrenToRemove.get(j);
                    // Note: We can not remove the view directly from CellLayoutChildren as this
                    // does not re-mark the spaces as unoccupied.
                    layoutParent.removeViewInLayout(child);
                    if (child instanceof DropTarget) {
                        mDragController.removeDropTarget((DropTarget) child);
                    }
                }

                if (childCount > 0) {
                    layout.requestLayout();
                    layout.invalidate();
                }
            }
        });
    }

    // Clean up new-apps animation list
    final Context context = getContext();
    post(new Runnable() {
        @Override
        public void run() {
            String spKey = LauncherApplication.getSharedPreferencesKey();
            SharedPreferences sp = context.getSharedPreferences(spKey, Context.MODE_PRIVATE);
            Set<String> newApps = sp.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, null);

            // Remove all queued items that match the same package
            if (newApps != null) {
                synchronized (newApps) {
                    Iterator<String> iter = newApps.iterator();
                    while (iter.hasNext()) {
                        try {
                            Intent intent = Intent.parseUri(iter.next(), 0);
                            String pn = ItemInfo.getPackageName(intent);
                            if (packageNames.contains(pn)) {
                                iter.remove();
                            }

                            // It is possible that we've queued an item to be loaded, yet it has
                            // not been added to the workspace, so remove those items as well.
                            ArrayList<ItemInfo> shortcuts;
                            shortcuts = LauncherModel.getWorkspaceShortcutItemInfosWithIntent(intent);
                            for (ItemInfo info : shortcuts) {
                                LauncherModel.deleteItemFromDatabase(context, info);
                            }
                        } catch (URISyntaxException e) {
                        }
                    }
                }
            }
        }
    });
}

From source file:com.android.launcher2.Launcher.java

/**
 * Add an application shortcut to the workspace.
 *
 * @param data The intent describing the application.
 * @param cellInfo The position on screen where to create the shortcut.
 */// w  w w. ja v a2  s . co m
void completeAddApplication(Intent data, long container, int screen, int cellX, int cellY) {
    final int[] cellXY = mTmpAddItemCellCoordinates;
    final CellLayout layout = getCellLayout(container, screen);

    // First we check if we already know the exact location where we want to add this item.
    if (cellX >= 0 && cellY >= 0) {
        cellXY[0] = cellX;
        cellXY[1] = cellY;
    } else if (!layout.findCellForSpan(cellXY, 1, 1)) {
        showOutOfSpaceMessage(isHotseatLayout(layout));
        return;
    }

    final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this);

    if (info != null) {
        info.setActivity(data.getComponent(),
                Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        info.container = ItemInfo.NO_ID;
        mWorkspace.addApplicationShortcut(info, layout, container, screen, cellXY[0], cellXY[1],
                isWorkspaceLocked(), cellX, cellY);
    } else {
        Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
    }
}

From source file:cc.flydev.launcher.Workspace.java

void updateShortcuts(ArrayList<AppInfo> apps) {
    ArrayList<ShortcutAndWidgetContainer> childrenLayouts = getAllShortcutAndWidgetContainers();
    for (ShortcutAndWidgetContainer layout : childrenLayouts) {
        int childCount = layout.getChildCount();
        for (int j = 0; j < childCount; j++) {
            final View view = layout.getChildAt(j);
            Object tag = view.getTag();

            if (LauncherModel.isShortcutInfoUpdateable((ItemInfo) tag)) {
                ShortcutInfo info = (ShortcutInfo) tag;

                final Intent intent = info.intent;
                final ComponentName name = intent.getComponent();
                final int appCount = apps.size();
                for (int k = 0; k < appCount; k++) {
                    AppInfo app = apps.get(k);
                    if (app.componentName.equals(name)) {
                        BubbleTextView shortcut = (BubbleTextView) view;
                        info.updateIcon(mIconCache);
                        info.title = app.title.toString();
                        shortcut.applyFromShortcutInfo(info, mIconCache);
                    }// w w w.j  a  va2s  . co  m
                }
            }
        }
    }
}

From source file:com.cognizant.trumobi.PersonaLauncher.java

private static PersonaApplicationInfo infoFromApplicationIntent(Context context, Intent data) {
    ComponentName component = data.getComponent();
    PackageManager packageManager = context.getPackageManager();
    ActivityInfo activityInfo = null;//from   w w w  .  j a  va2 s .co  m
    try {
        activityInfo = packageManager.getActivityInfo(component, 0 /*
                                                                   * no
                                                                   * flags
                                                                   */);
    } catch (NameNotFoundException e) {
        PersonaLog.e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e);
    }

    if (activityInfo != null) {
        PersonaApplicationInfo itemInfo = new PersonaApplicationInfo();

        itemInfo.title = activityInfo.loadLabel(packageManager);
        if (itemInfo.title == null) {
            itemInfo.title = activityInfo.name;
        }

        itemInfo.setActivity(component,
                Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        // itemInfo.icon = activityInfo.loadIcon(packageManager);
        itemInfo.container = PersonaItemInfo.NO_ID;

        itemInfo.icon = PersonaLauncherModel.getIcon(packageManager, context, activityInfo);

        return itemInfo;
    }

    return null;
}

From source file:com.tasomaniac.openwith.resolver.ResolverActivity.java

protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) {

    final ChooserHistory history = getHistory();

    if ((mAlwaysUseOption || mAdapter.hasFilteredItem()) && mAdapter.mOrigResolveList != null) {
        // Build a reasonable intent filter, based on what matched.
        IntentFilter filter = new IntentFilter();

        if (intent.getAction() != null) {
            filter.addAction(intent.getAction());
        }//from w w w.j  a v  a  2s.c  o m
        Set<String> categories = intent.getCategories();
        if (categories != null) {
            for (String cat : categories) {
                filter.addCategory(cat);
            }
        }
        filter.addCategory(Intent.CATEGORY_DEFAULT);

        int cat = ri.match & IntentFilter.MATCH_CATEGORY_MASK;
        Uri data = intent.getData();
        if (cat == IntentFilter.MATCH_CATEGORY_TYPE) {
            String mimeType = intent.resolveType(this);
            if (mimeType != null) {
                try {
                    filter.addDataType(mimeType);
                } catch (IntentFilter.MalformedMimeTypeException e) {
                    Log.w("ResolverActivity", e);
                    filter = null;
                }
            }
        }
        if (filter != null && data != null && data.getScheme() != null) {
            // We need the data specification if there was no type,
            // OR if the scheme is not one of our magical "file:"
            // or "content:" schemes (see IntentFilter for the reason).
            if (cat != IntentFilter.MATCH_CATEGORY_TYPE
                    || (!"file".equals(data.getScheme()) && !"content".equals(data.getScheme()))) {
                filter.addDataScheme(data.getScheme());

                // Look through the resolved filter to determine which part
                // of it matched the original Intent.
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                    Iterator<PatternMatcher> pIt = ri.filter.schemeSpecificPartsIterator();

                    if (pIt != null) {
                        String ssp = data.getSchemeSpecificPart();
                        while (ssp != null && pIt.hasNext()) {
                            PatternMatcher p = pIt.next();
                            if (p.match(ssp)) {
                                filter.addDataSchemeSpecificPart(p.getPath(), p.getType());
                                break;
                            }
                        }
                    }
                }
                Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator();
                if (aIt != null) {
                    while (aIt.hasNext()) {
                        IntentFilter.AuthorityEntry a = aIt.next();
                        if (a.match(data) >= 0) {
                            int port = a.getPort();
                            filter.addDataAuthority(a.getHost(), port >= 0 ? Integer.toString(port) : null);
                            break;
                        }
                    }
                }
                Iterator<PatternMatcher> pIt = ri.filter.pathsIterator();
                if (pIt != null) {
                    String path = data.getPath();
                    while (path != null && pIt.hasNext()) {
                        PatternMatcher p = pIt.next();
                        if (p.match(path)) {
                            filter.addDataPath(p.getPath(), p.getType());
                            break;
                        }
                    }
                }
            }
        }

        if (filter != null) {
            ContentValues values = new ContentValues(3);
            values.put(HOST, mRequestedUri.getHost());
            values.put(COMPONENT, intent.getComponent().flattenToString());

            if (alwaysCheck) {
                values.put(PREFERRED, true);
            }
            values.put(LAST_CHOSEN, true);
            getContentResolver().insert(CONTENT_URI, values);

            history.add(intent.getComponent().getPackageName());
        }
    }

    if (intent != null) {
        startActivity(intent);
    }
    history.save(this);
}

From source file:com.aidy.launcher3.ui.workspace.Workspace.java

public void updateShortcuts(ArrayList<AppInfoBean> apps) {
    ArrayList<ShortcutAndWidgetContainer> childrenLayouts = getAllShortcutAndWidgetContainers();
    for (ShortcutAndWidgetContainer layout : childrenLayouts) {
        int childCount = layout.getChildCount();
        for (int j = 0; j < childCount; j++) {
            final View view = layout.getChildAt(j);
            Object tag = view.getTag();

            if (LauncherModel.isShortcutInfoUpdateable((ItemInfoBean) tag)) {
                ShortcutInfo info = (ShortcutInfo) tag;

                final Intent intent = info.intent;
                final ComponentName name = intent.getComponent();
                final int appCount = apps.size();
                for (int k = 0; k < appCount; k++) {
                    AppInfoBean app = apps.get(k);
                    if (app.componentName.equals(name)) {
                        BubbleTextView shortcut = (BubbleTextView) view;
                        info.updateIcon(mIconCache);
                        info.title = app.title.toString();
                        shortcut.applyFromShortcutInfo(info, mIconCache);
                    }//  ww  w.  j a v  a 2 s  . com
                }
            }
        }
    }
}

From source file:com.android.leanlauncher.LauncherTransitionable.java

boolean startActivity(View v, Intent intent, Object tag) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {// www . j a  v a  2 s . c o  m
        // Only launch using the new animation if the shortcut has not opted out (this is a
        // private contract between launcher and may be ignored in the future).
        boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
        LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(this);
        UserManagerCompat userManager = UserManagerCompat.getInstance(this);

        UserHandleCompat user = null;
        if (intent.hasExtra(AppInfo.EXTRA_PROFILE)) {
            long serialNumber = intent.getLongExtra(AppInfo.EXTRA_PROFILE, -1);
            user = userManager.getUserForSerialNumber(serialNumber);
        }

        Bundle optsBundle = null;
        if (useLaunchAnimation) {
            ActivityOptions opts = Utilities.isLmpOrAbove()
                    ? ActivityOptions.makeCustomAnimation(this, R.anim.task_open_enter, R.anim.no_anim)
                    : ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getMeasuredWidth(),
                            v.getMeasuredHeight());
            optsBundle = opts.toBundle();
        }

        if (user == null || user.equals(UserHandleCompat.myUserHandle())) {
            // Could be launching some bookkeeping activity
            startActivity(intent, optsBundle);
        } else {
            // TODO Component can be null when shortcuts are supported for secondary user
            launcherApps.startActivityForProfile(intent.getComponent(), user, intent.getSourceBounds(),
                    optsBundle);
        }
        return true;
    } catch (SecurityException e) {
        Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
        Log.e(TAG, "Launcher does not have the permission to launch " + intent
                + ". Make sure to create a MAIN intent-filter for the corresponding activity "
                + "or use the exported attribute for this activity. " + "tag=" + tag + " intent=" + intent, e);
    }
    return false;
}

From source file:com.klinker.android.launcher.launcher3.Launcher.java

/**
 * Event handler for an app shortcut click.
 *
 * @param v The view that was clicked. Must be a tagged with a {@link ShortcutInfo}.
 *//*from   w w  w  .j  a v  a  2  s  .  co  m*/
protected void onClickAppShortcut(final View v) {
    if (LOGD)
        Log.d(TAG, "onClickAppShortcut");
    Object tag = v.getTag();
    if (!(tag instanceof ShortcutInfo)) {
        throw new IllegalArgumentException("Input must be a Shortcut");
    }

    // Open shortcut
    final ShortcutInfo shortcut = (ShortcutInfo) tag;

    if (shortcut.isDisabled != 0) {
        int error = R.string.activity_not_available;
        if ((shortcut.isDisabled & ShortcutInfo.FLAG_DISABLED_SAFEMODE) != 0) {
            error = R.string.safemode_shortcut_error;
        }
        Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
        return;
    }

    final Intent intent = shortcut.intent;

    // Check for special shortcuts
    if (intent.getComponent() != null) {
        final String shortcutClass = intent.getComponent().getClassName();

        if (shortcutClass.equals(MemoryDumpActivity.class.getName())) {
            MemoryDumpActivity.startDump(this);
            return;
        } else if (shortcutClass.equals(ToggleWeightWatcher.class.getName())) {
            toggleShowWeightWatcher();
            return;
        }
    }

    // Check for abandoned promise
    if ((v instanceof BubbleTextView) && shortcut.isPromise()
            && !shortcut.hasStatusFlag(ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE)) {
        showBrokenAppInstallDialog(shortcut.getTargetComponent().getPackageName(),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        startAppShortcutOrInfoActivity(v);
                    }
                });
        return;
    }

    // Start activities
    startAppShortcutOrInfoActivity(v);

    if (mLauncherCallbacks != null) {
        mLauncherCallbacks.onClickAppShortcut(v);
    }
}