Example usage for android.app SearchManager QUERY

List of usage examples for android.app SearchManager QUERY

Introduction

In this page you can find the example usage for android.app SearchManager QUERY.

Prototype

String QUERY

To view the source code for android.app SearchManager QUERY.

Click Source Link

Document

Intent extra data key: Use this key with android.content.Intent#getStringExtra content.Intent.getStringExtra() to obtain the query string from Intent.ACTION_SEARCH.

Usage

From source file:org.transdroid.gui.TorrentsFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case ACTIVITY_PREFERENCES:

        // Preference screen was called: use new preferences to connect
        readSettings();//from  ww w. j av  a2  s .com
        setupDaemon();
        updateTorrentList();
        break;

    case ACTIVITY_DETAILS:

        // Details screen was shown; we may have an updated torrent (it can be started/removed/etc.)
        updateTorrentList();
        break;

    case ACTIVITY_BARCODE:

        if (resultCode == Activity.RESULT_OK) {

            // Get scan results code
            String contents = data.getStringExtra("SCAN_RESULT");
            String formatName = data.getStringExtra("SCAN_RESULT_FORMAT");

            if (formatName != null && formatName.equals(Transdroid.SCAN_FORMAT_QRCODE)) {
                // Scanned barcode was a QR code: assume the contents contain a URL to a .torrent file
                TLog.d(LOG_NAME, "Add torrent from QR code url '" + contents + "'");
                addTorrentByUrl(contents, "Torrent QR code"); // No real torrent title known
            } else {
                // Get a meaningful search query based on a Google Search product lookup
                TLog.d(LOG_NAME,
                        "Starting barcode lookup for code '" + contents + "' "
                                + (formatName == null ? "(code type is unknown)"
                                        : "(this should be a " + formatName + " code)"));
                setProgressBar(true);
                new GoogleWebSearchBarcodeResolver() {
                    @Override
                    protected void onBarcodeLookupComplete(String result) {

                        setProgressBar(false);

                        // No proper result?
                        if (result == null || result.equals("")) {
                            TLog.d(LOG_NAME, "Barcode not resolved (timout, connection error, no items, etc.)");
                            Toast.makeText(getActivity(), R.string.no_results, Toast.LENGTH_SHORT).show();
                            return;
                        }

                        // Open TransdroidSearch directly, mimicking a search query
                        TLog.d(LOG_NAME, "Barcode resolved to '" + result + "'. Now starting search.");
                        Intent search = new Intent(getActivity(), Search.class);
                        search.setAction(Intent.ACTION_SEARCH);
                        search.putExtra(SearchManager.QUERY, result);
                        startActivity(search);

                    }
                }.execute(contents);
            }

        }
        break;
    }
}

From source file:it.feio.android.omninotes.ListFragment.java

/**
 * Search notes by tags//ww w  .  j  a  v  a 2 s  .com
 */
private void filterByTags() {

    // Retrieves all available categories
    final List<Tag> tags = TagsHelper.getAllTags();

    // If there is no category a message will be shown
    if (tags.size() == 0) {
        mainActivity.showMessage(R.string.no_tags_created, ONStyle.WARN);
        return;
    }

    // Dialog and events creation
    new MaterialDialog.Builder(mainActivity).title(R.string.select_tags).items(TagsHelper.getTagsArray(tags))
            .positiveText(R.string.ok).itemsCallbackMultiChoice(new Integer[] {}, (dialog, which, text) -> {
                // Retrieves selected tags
                List<String> selectedTags = new ArrayList<>();
                for (Integer aWhich : which) {
                    selectedTags.add(tags.get(aWhich).getText());
                }

                // Saved here to allow persisting search
                searchTags = selectedTags.toString().substring(1, selectedTags.toString().length() - 1)
                        .replace(" ", "");
                Intent intent = mainActivity.getIntent();

                // Hides keyboard
                searchView.clearFocus();
                KeyboardUtils.hideKeyboard(searchView);

                intent.removeExtra(SearchManager.QUERY);
                initNotesList(intent);
                return false;
            }).build().show();
}

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

/**
 * Starts the global search activity. This code is a copied from SearchManager
 *//*from w  ww  .ja  v a 2 s .  c  o  m*/
public void startGlobalSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData,
        Rect sourceBounds) {
    final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
    if (globalSearchActivity == null) {
        Log.w(TAG, "No global search activity found.");
        return;
    }
    Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setComponent(globalSearchActivity);
    // Make sure that we have a Bundle to put source in
    if (appSearchData == null) {
        appSearchData = new Bundle();
    } else {
        appSearchData = new Bundle(appSearchData);
    }
    // Set source to package name of app that starts global search, if not set already.
    if (!appSearchData.containsKey("source")) {
        appSearchData.putString("source", getPackageName());
    }
    intent.putExtra(SearchManager.APP_DATA, appSearchData);
    if (!TextUtils.isEmpty(initialQuery)) {
        intent.putExtra(SearchManager.QUERY, initialQuery);
    }
    if (selectInitialQuery) {
        intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
    }
    intent.setSourceBounds(sourceBounds);
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException ex) {
        Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
    }
}

From source file:com.dycody.android.idealnote.ListFragment.java

/**
 * Search notes by tags//w  ww.j  a va  2s . com
 */
private void filterByTags() {

    // Retrieves all available categories
    final List<Tag> tags = TagsHelper.getAllTags();

    // If there is no category a message will be shown
    if (tags.size() == 0) {
        //mainActivity.showMessage(R.string.no_tags_created, ONStyle.WARN);
        Toast.makeText(getActivity(), R.string.no_tags_created, Toast.LENGTH_SHORT).show();
        return;
    }

    // Dialog and events creation
    new MaterialDialog.Builder(mainActivity).title(R.string.select_tags).items(TagsHelper.getTagsArray(tags))
            .positiveText(R.string.ok).itemsCallbackMultiChoice(new Integer[] {}, (dialog, which, text) -> {
                // Retrieves selected tags
                List<String> selectedTags = new ArrayList<>();
                for (Integer aWhich : which) {
                    selectedTags.add(tags.get(aWhich).getText());
                }

                // Saved here to allow persisting search
                searchTags = selectedTags.toString().substring(1, selectedTags.toString().length() - 1)
                        .replace(" ", "");
                Intent intent = mainActivity.getIntent();

                // Hides keyboard
                searchView.clearFocus();
                KeyboardUtils.hideKeyboard(searchView);

                intent.removeExtra(SearchManager.QUERY);
                initNotesList(intent);
                return false;
            }).build().show();
}

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

/**
 * Starts the global search activity. This code is a copied from SearchManager
 *///from   w  w w.j av a  2 s  .  com
private void startGlobalSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData,
        Rect sourceBounds) {
    final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
    if (globalSearchActivity == null) {
        Log.w(TAG, "No global search activity found.");
        return;
    }
    Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setComponent(globalSearchActivity);
    // Make sure that we have a Bundle to put source in
    if (appSearchData == null) {
        appSearchData = new Bundle();
    } else {
        appSearchData = new Bundle(appSearchData);
    }
    // Set source to package name of app that starts global search, if not set already.
    if (!appSearchData.containsKey("source")) {
        appSearchData.putString("source", getPackageName());
    }
    intent.putExtra(SearchManager.APP_DATA, appSearchData);
    if (!TextUtils.isEmpty(initialQuery)) {
        intent.putExtra(SearchManager.QUERY, initialQuery);
    }
    if (selectInitialQuery) {
        intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
    }
    intent.setSourceBounds(sourceBounds);
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException ex) {
        Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
    }
}

From source file:com.android.contacts.quickcontact.QuickContactActivity.java

/**
 * Converts a {@link DataItem} into an {@link ExpandingEntryCardView.Entry} for display.
 * If the {@link ExpandingEntryCardView.Entry} has no visual elements, null is returned.
 *
 * This runs on a background thread. This is set as static to avoid accidentally adding
 * additional dependencies on unsafe things (like the Activity).
 *
 * @param dataItem The {@link DataItem} to convert.
 * @param secondDataItem A second {@link DataItem} to help build a full entry for some
 *  mimetypes/* w w w.  ja va2  s .  c o  m*/
 * @return The {@link ExpandingEntryCardView.Entry}, or null if no visual elements are present.
 */
private static Entry dataItemToEntry(DataItem dataItem, DataItem secondDataItem, Context context,
        Contact contactData, final MutableString aboutCardName) {
    Drawable icon = null;
    String header = null;
    String subHeader = null;
    Drawable subHeaderIcon = null;
    String text = null;
    Drawable textIcon = null;
    StringBuilder primaryContentDescription = new StringBuilder();
    Spannable phoneContentDescription = null;
    Spannable smsContentDescription = null;
    Intent intent = null;
    boolean shouldApplyColor = true;
    Drawable alternateIcon = null;
    Intent alternateIntent = null;
    StringBuilder alternateContentDescription = new StringBuilder();
    final boolean isEditable = false;
    EntryContextMenuInfo entryContextMenuInfo = null;
    Drawable thirdIcon = null;
    Intent thirdIntent = null;
    int thirdAction = Entry.ACTION_NONE;
    String thirdContentDescription = null;
    Bundle thirdExtras = null;
    int iconResourceId = 0;

    context = context.getApplicationContext();
    final Resources res = context.getResources();
    DataKind kind = dataItem.getDataKind();

    if (dataItem instanceof ImDataItem) {
        final ImDataItem im = (ImDataItem) dataItem;
        intent = ContactsUtils.buildImIntent(context, im).first;
        final boolean isEmail = im.isCreatedFromEmail();
        final int protocol;
        if (!im.isProtocolValid()) {
            protocol = Im.PROTOCOL_CUSTOM;
        } else {
            protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK : im.getProtocol();
        }
        if (protocol == Im.PROTOCOL_CUSTOM) {
            // If the protocol is custom, display the "IM" entry header as well to distinguish
            // this entry from other ones
            header = res.getString(R.string.header_im_entry);
            subHeader = Im.getProtocolLabel(res, protocol, im.getCustomProtocol()).toString();
            text = im.getData();
        } else {
            header = Im.getProtocolLabel(res, protocol, im.getCustomProtocol()).toString();
            subHeader = im.getData();
        }
        entryContextMenuInfo = new EntryContextMenuInfo(im.getData(), header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
    } else if (dataItem instanceof OrganizationDataItem) {
        final OrganizationDataItem organization = (OrganizationDataItem) dataItem;
        header = res.getString(R.string.header_organization_entry);
        subHeader = organization.getCompany();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        text = organization.getTitle();
    } else if (dataItem instanceof NicknameDataItem) {
        final NicknameDataItem nickname = (NicknameDataItem) dataItem;
        // Build nickname entries
        final boolean isNameRawContact = (contactData.getNameRawContactId() == dataItem.getRawContactId());

        final boolean duplicatesTitle = isNameRawContact
                && contactData.getDisplayNameSource() == DisplayNameSources.NICKNAME;

        if (!duplicatesTitle) {
            header = res.getString(R.string.header_nickname_entry);
            subHeader = nickname.getName();
            entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                    dataItem.getId(), dataItem.isSuperPrimary());
        }
    } else if (dataItem instanceof NoteDataItem) {
        final NoteDataItem note = (NoteDataItem) dataItem;
        header = res.getString(R.string.header_note_entry);
        subHeader = note.getNote();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
    } else if (dataItem instanceof WebsiteDataItem) {
        final WebsiteDataItem website = (WebsiteDataItem) dataItem;
        header = res.getString(R.string.header_website_entry);
        subHeader = website.getUrl();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        try {
            final WebAddress webAddress = new WebAddress(website.buildDataStringForDisplay(context, kind));
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webAddress.toString()));
        } catch (final ParseException e) {
            Log.e(TAG, "Couldn't parse website: " + website.buildDataStringForDisplay(context, kind));
        }
    } else if (dataItem instanceof EventDataItem) {
        final EventDataItem event = (EventDataItem) dataItem;
        final String dataString = event.buildDataStringForDisplay(context, kind);
        final Calendar cal = DateUtils.parseDate(dataString, false);
        if (cal != null) {
            final Date nextAnniversary = DateUtils.getNextAnnualDate(cal);
            final Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
            builder.appendPath("time");
            ContentUris.appendId(builder, nextAnniversary.getTime());
            intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
        }
        header = res.getString(R.string.header_event_entry);
        if (event.hasKindTypeColumn(kind)) {
            subHeader = EventCompat.getTypeLabel(res, event.getKindTypeColumn(kind), event.getLabel())
                    .toString();
        }
        text = DateUtils.formatDate(context, dataString);
        entryContextMenuInfo = new EntryContextMenuInfo(text, header, dataItem.getMimeType(), dataItem.getId(),
                dataItem.isSuperPrimary());
    } else if (dataItem instanceof RelationDataItem) {
        final RelationDataItem relation = (RelationDataItem) dataItem;
        final String dataString = relation.buildDataStringForDisplay(context, kind);
        if (!TextUtils.isEmpty(dataString)) {
            intent = new Intent(Intent.ACTION_SEARCH);
            intent.putExtra(SearchManager.QUERY, dataString);
            intent.setType(Contacts.CONTENT_TYPE);
        }
        header = res.getString(R.string.header_relation_entry);
        subHeader = relation.getName();
        entryContextMenuInfo = new EntryContextMenuInfo(subHeader, header, dataItem.getMimeType(),
                dataItem.getId(), dataItem.isSuperPrimary());
        if (relation.hasKindTypeColumn(kind)) {
            text = Relation.getTypeLabel(res, relation.getKindTypeColumn(kind), relation.getLabel()).toString();
        }
    } else if (dataItem instanceof PhoneDataItem) {
        final PhoneDataItem phone = (PhoneDataItem) dataItem;
        String phoneLabel = null;
        if (!TextUtils.isEmpty(phone.getNumber())) {
            primaryContentDescription.append(res.getString(R.string.call_other)).append(" ");
            header = sBidiFormatter.unicodeWrap(phone.buildDataStringForDisplay(context, kind),
                    TextDirectionHeuristics.LTR);
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.phoneLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (phone.hasKindTypeColumn(kind)) {
                final int kindTypeColumn = phone.getKindTypeColumn(kind);
                final String label = phone.getLabel();
                phoneLabel = label;
                if (kindTypeColumn == Phone.TYPE_CUSTOM && TextUtils.isEmpty(label)) {
                    text = "";
                } else {
                    text = Phone.getTypeLabel(res, kindTypeColumn, label).toString();
                    phoneLabel = text;
                    primaryContentDescription.append(text).append(" ");
                }
            }
            primaryContentDescription.append(header);
            phoneContentDescription = com.android.contacts.common.util.ContactDisplayUtils
                    .getTelephoneTtsSpannable(primaryContentDescription.toString(), header);
            icon = res.getDrawable(R.drawable.ic_phone_24dp);
            iconResourceId = R.drawable.ic_phone_24dp;
            if (PhoneCapabilityTester.isPhone(context)) {
                intent = CallUtil.getCallIntent(phone.getNumber());
            }
            alternateIntent = new Intent(Intent.ACTION_SENDTO,
                    Uri.fromParts(ContactsUtils.SCHEME_SMSTO, phone.getNumber(), null));

            alternateIcon = res.getDrawable(R.drawable.ic_message_24dp);
            alternateContentDescription.append(res.getString(R.string.sms_custom, header));
            smsContentDescription = com.android.contacts.common.util.ContactDisplayUtils
                    .getTelephoneTtsSpannable(alternateContentDescription.toString(), header);

            int videoCapability = CallUtil.getVideoCallingAvailability(context);
            boolean isPresenceEnabled = (videoCapability & CallUtil.VIDEO_CALLING_PRESENCE) != 0;
            boolean isVideoEnabled = (videoCapability & CallUtil.VIDEO_CALLING_ENABLED) != 0;

            if (CallUtil.isCallWithSubjectSupported(context)) {
                thirdIcon = res.getDrawable(R.drawable.ic_call_note_white_24dp);
                thirdAction = Entry.ACTION_CALL_WITH_SUBJECT;
                thirdContentDescription = res.getString(R.string.call_with_a_note);
                // Create a bundle containing the data the call subject dialog requires.
                thirdExtras = new Bundle();
                thirdExtras.putLong(CallSubjectDialog.ARG_PHOTO_ID, contactData.getPhotoId());
                thirdExtras.putParcelable(CallSubjectDialog.ARG_PHOTO_URI,
                        UriUtils.parseUriOrNull(contactData.getPhotoUri()));
                thirdExtras.putParcelable(CallSubjectDialog.ARG_CONTACT_URI, contactData.getLookupUri());
                thirdExtras.putString(CallSubjectDialog.ARG_NAME_OR_NUMBER, contactData.getDisplayName());
                thirdExtras.putBoolean(CallSubjectDialog.ARG_IS_BUSINESS, false);
                thirdExtras.putString(CallSubjectDialog.ARG_NUMBER, phone.getNumber());
                thirdExtras.putString(CallSubjectDialog.ARG_DISPLAY_NUMBER, phone.getFormattedPhoneNumber());
                thirdExtras.putString(CallSubjectDialog.ARG_NUMBER_LABEL, phoneLabel);
            } else if (isVideoEnabled) {
                // Check to ensure carrier presence indicates the number supports video calling.
                int carrierPresence = dataItem.getCarrierPresence();
                boolean isPresent = (carrierPresence & Phone.CARRIER_PRESENCE_VT_CAPABLE) != 0;

                if ((isPresenceEnabled && isPresent) || !isPresenceEnabled) {
                    thirdIcon = res.getDrawable(R.drawable.ic_videocam);
                    thirdAction = Entry.ACTION_INTENT;
                    thirdIntent = CallUtil.getVideoCallIntent(phone.getNumber(),
                            CALL_ORIGIN_QUICK_CONTACTS_ACTIVITY);
                    thirdContentDescription = res.getString(R.string.description_video_call);
                }
            }
        }
    } else if (dataItem instanceof EmailDataItem) {
        final EmailDataItem email = (EmailDataItem) dataItem;
        final String address = email.getData();
        if (!TextUtils.isEmpty(address)) {
            primaryContentDescription.append(res.getString(R.string.email_other)).append(" ");
            final Uri mailUri = Uri.fromParts(ContactsUtils.SCHEME_MAILTO, address, null);
            intent = new Intent(Intent.ACTION_SENDTO, mailUri);
            header = email.getAddress();
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.emailLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (email.hasKindTypeColumn(kind)) {
                text = Email.getTypeLabel(res, email.getKindTypeColumn(kind), email.getLabel()).toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            icon = res.getDrawable(R.drawable.ic_email_24dp);
            iconResourceId = R.drawable.ic_email_24dp;
        }
    } else if (dataItem instanceof StructuredPostalDataItem) {
        StructuredPostalDataItem postal = (StructuredPostalDataItem) dataItem;
        final String postalAddress = postal.getFormattedAddress();
        if (!TextUtils.isEmpty(postalAddress)) {
            primaryContentDescription.append(res.getString(R.string.map_other)).append(" ");
            intent = StructuredPostalUtils.getViewPostalAddressIntent(postalAddress);
            header = postal.getFormattedAddress();
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.postalLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (postal.hasKindTypeColumn(kind)) {
                text = StructuredPostal.getTypeLabel(res, postal.getKindTypeColumn(kind), postal.getLabel())
                        .toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            alternateIntent = StructuredPostalUtils.getViewPostalAddressDirectionsIntent(postalAddress);
            alternateIcon = res.getDrawable(R.drawable.ic_directions_24dp);
            alternateContentDescription.append(res.getString(R.string.content_description_directions))
                    .append(" ").append(header);
            icon = res.getDrawable(R.drawable.ic_place_24dp);
            iconResourceId = R.drawable.ic_place_24dp;
        }
    } else if (dataItem instanceof SipAddressDataItem) {
        final SipAddressDataItem sip = (SipAddressDataItem) dataItem;
        final String address = sip.getSipAddress();
        if (!TextUtils.isEmpty(address)) {
            primaryContentDescription.append(res.getString(R.string.call_other)).append(" ");
            if (PhoneCapabilityTester.isSipPhone(context)) {
                final Uri callUri = Uri.fromParts(PhoneAccount.SCHEME_SIP, address, null);
                intent = CallUtil.getCallIntent(callUri);
            }
            header = address;
            entryContextMenuInfo = new EntryContextMenuInfo(header, res.getString(R.string.phoneLabelsGroup),
                    dataItem.getMimeType(), dataItem.getId(), dataItem.isSuperPrimary());
            if (sip.hasKindTypeColumn(kind)) {
                text = SipAddress.getTypeLabel(res, sip.getKindTypeColumn(kind), sip.getLabel()).toString();
                primaryContentDescription.append(text).append(" ");
            }
            primaryContentDescription.append(header);
            icon = res.getDrawable(R.drawable.ic_dialer_sip_black_24dp);
            iconResourceId = R.drawable.ic_dialer_sip_black_24dp;
        }
    } else if (dataItem instanceof StructuredNameDataItem) {
        // If the name is already set and this is not the super primary value then leave the
        // current value. This way we show the super primary value when we are able to.
        if (dataItem.isSuperPrimary() || aboutCardName.value == null || aboutCardName.value.isEmpty()) {
            final String givenName = ((StructuredNameDataItem) dataItem).getGivenName();
            if (!TextUtils.isEmpty(givenName)) {
                aboutCardName.value = res.getString(R.string.about_card_title) + " " + givenName;
            } else {
                aboutCardName.value = res.getString(R.string.about_card_title);
            }
        }
    } else {
        // Custom DataItem
        header = dataItem.buildDataStringForDisplay(context, kind);
        text = kind.typeColumn;
        intent = new Intent(Intent.ACTION_VIEW);
        final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, dataItem.getId());
        intent.setDataAndType(uri, dataItem.getMimeType());

        if (intent != null) {
            final String mimetype = intent.getType();

            // Build advanced entry for known 3p types. Otherwise default to ResolveCache icon.
            switch (mimetype) {
            case MIMETYPE_GPLUS_PROFILE:
                // If a secondDataItem is available, use it to build an entry with
                // alternate actions
                if (secondDataItem != null) {
                    icon = res.getDrawable(R.drawable.ic_google_plus_24dp);
                    alternateIcon = res.getDrawable(R.drawable.ic_add_to_circles_black_24);
                    final GPlusOrHangoutsDataItemModel itemModel = new GPlusOrHangoutsDataItemModel(intent,
                            alternateIntent, dataItem, secondDataItem, alternateContentDescription, header,
                            text, context);

                    populateGPlusOrHangoutsDataItemModel(itemModel);
                    intent = itemModel.intent;
                    alternateIntent = itemModel.alternateIntent;
                    alternateContentDescription = itemModel.alternateContentDescription;
                    header = itemModel.header;
                    text = itemModel.text;
                } else {
                    if (GPLUS_PROFILE_DATA_5_ADD_TO_CIRCLE.equals(intent.getDataString())) {
                        icon = res.getDrawable(R.drawable.ic_add_to_circles_black_24);
                    } else {
                        icon = res.getDrawable(R.drawable.ic_google_plus_24dp);
                    }
                }
                break;
            case MIMETYPE_HANGOUTS:
                // If a secondDataItem is available, use it to build an entry with
                // alternate actions
                if (secondDataItem != null) {
                    icon = res.getDrawable(R.drawable.ic_hangout_24dp);
                    alternateIcon = res.getDrawable(R.drawable.ic_hangout_video_24dp);
                    final GPlusOrHangoutsDataItemModel itemModel = new GPlusOrHangoutsDataItemModel(intent,
                            alternateIntent, dataItem, secondDataItem, alternateContentDescription, header,
                            text, context);

                    populateGPlusOrHangoutsDataItemModel(itemModel);
                    intent = itemModel.intent;
                    alternateIntent = itemModel.alternateIntent;
                    alternateContentDescription = itemModel.alternateContentDescription;
                    header = itemModel.header;
                    text = itemModel.text;
                } else {
                    if (HANGOUTS_DATA_5_VIDEO.equals(intent.getDataString())) {
                        icon = res.getDrawable(R.drawable.ic_hangout_video_24dp);
                    } else {
                        icon = res.getDrawable(R.drawable.ic_hangout_24dp);
                    }
                }
                break;
            default:
                entryContextMenuInfo = new EntryContextMenuInfo(header, mimetype, dataItem.getMimeType(),
                        dataItem.getId(), dataItem.isSuperPrimary());
                icon = ResolveCache.getInstance(context).getIcon(dataItem.getMimeType(), intent);
                // Call mutate to create a new Drawable.ConstantState for color filtering
                if (icon != null) {
                    icon.mutate();
                }
                shouldApplyColor = false;
            }
        }
    }

    if (intent != null) {
        // Do not set the intent is there are no resolves
        if (!PhoneCapabilityTester.isIntentRegistered(context, intent)) {
            intent = null;
        }
    }

    if (alternateIntent != null) {
        // Do not set the alternate intent is there are no resolves
        if (!PhoneCapabilityTester.isIntentRegistered(context, alternateIntent)) {
            alternateIntent = null;
        } else if (TextUtils.isEmpty(alternateContentDescription)) {
            // Attempt to use package manager to find a suitable content description if needed
            alternateContentDescription.append(getIntentResolveLabel(alternateIntent, context));
        }
    }

    // If the Entry has no visual elements, return null
    if (icon == null && TextUtils.isEmpty(header) && TextUtils.isEmpty(subHeader) && subHeaderIcon == null
            && TextUtils.isEmpty(text) && textIcon == null) {
        return null;
    }

    // Ignore dataIds from the Me profile.
    final int dataId = dataItem.getId() > Integer.MAX_VALUE ? -1 : (int) dataItem.getId();

    return new Entry(dataId, icon, header, subHeader, subHeaderIcon, text, textIcon,
            phoneContentDescription == null ? new SpannableString(primaryContentDescription.toString())
                    : phoneContentDescription,
            intent, alternateIcon, alternateIntent,
            smsContentDescription == null ? new SpannableString(alternateContentDescription.toString())
                    : smsContentDescription,
            shouldApplyColor, isEditable, entryContextMenuInfo, thirdIcon, thirdIntent, thirdContentDescription,
            thirdAction, thirdExtras, iconResourceId);
}

From source file:com.tct.mail.ui.AbstractActivityController.java

/**
 * The application can be started from the following entry points:
 * <ul>//from w  w  w .j ava  2s .co m
 *     <li>Launcher: you tap on the Gmail icon in the launcher. This is what most users think of
 *         as Starting the app?.</li>
 *     <li>Shortcut: Users can make a shortcut to take them directly to a label.</li>
 *     <li>Widget: Shows the contents of a synced label, and allows:
 *     <ul>
 *         <li>Viewing the list (tapping on the title)</li>
 *         <li>Composing a new message (tapping on the new message icon in the title. This
 *         launches the {@link ComposeActivity}.
 *         </li>
 *         <li>Viewing a single message (tapping on a list element)</li>
 *     </ul>
 *
 *     </li>
 *     <li>Tapping on a notification:
 *     <ul>
 *         <li>Shows message list if more than one message</li>
 *         <li>Shows the conversation if the notification is for a single message</li>
 *     </ul>
 *     </li>
 *     <li>...and most importantly, the activity life cycle can tear down the application and
 *     restart it:
 *     <ul>
 *         <li>Rotate the application: it is destroyed and recreated.</li>
 *         <li>Navigate away, and return from recent applications.</li>
 *     </ul>
 *     </li>
 *     <li>Add a new account: fires off an intent to add an account,
 *     and returns in {@link #onActivityResult(int, int, android.content.Intent)} .</li>
 *     <li>Re-authenticate your account: again returns in onActivityResult().</li>
 *     <li>Composing can happen from many entry points: third party applications fire off an
 *     intent to compose email, and launch directly into the {@link ComposeActivity}
 *     .</li>
 * </ul>
 * {@inheritDoc}
 */
@SuppressLint("NewApi")
@Override
public boolean onCreate(Bundle savedState) {
    initializeActionBar();
    initializeDevLoggingService();
    // Allow shortcut keys to function for the ActionBar and menus.
    mActivity.setDefaultKeyMode(Activity.DEFAULT_KEYS_SHORTCUT);
    mResolver = mActivity.getContentResolver();
    mNewEmailReceiver = new SuppressNotificationReceiver();
    mRecentFolderList.initialize(mActivity);
    mVeiledMatcher.initialize(this);

    mFloatingComposeButton = mActivity.findViewById(R.id.compose_button);

    //TS: ke.ma 2015-03-12 EMAIL BUGFIX-947440 ADD_S
    mFloatingComposeButton.setElevation(8);
    mFloatingComposeButton.setOutlineProvider(new ViewOutlineProvider() {

        @Override
        public void getOutline(View view, Outline outline) {
            // TODO Auto-generated method stub
            outline.setOval(0, 0, view.getWidth(), view.getWidth());
        }
    });
    //TS: ke.ma 2015-03-12 EMAIL BUGFIX-947440 ADD_E
    mFloatingComposeButton.setOnClickListener(this);

    if (isDrawerEnabled()) {
        mDrawerToggle = new ActionBarDrawerToggle(mActivity, mDrawerContainer,
                //                    false,
                //                    R.drawable.ic_drawer,
                R.string.drawer_open, R.string.drawer_close);
        mDrawerContainer.setDrawerListener(mDrawerListener);
        mDrawerContainer.setDrawerShadow(mContext.getResources().getDrawable(R.drawable.drawer_shadow),
                Gravity.START);

        mDrawerToggle.setDrawerIndicatorEnabled(isDrawerEnabled());
    } else {
        final ActionBar ab = mActivity.getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_drawer);
        ab.setHomeActionContentDescription(R.string.drawer_open);
        ab.setDisplayHomeAsUpEnabled(true);
    }

    // All the individual UI components listen for ViewMode changes. This
    // simplifies the amount of logic in the AbstractActivityController, but increases the
    // possibility of timing-related bugs.
    mViewMode.addListener(this);
    mPagerController = new ConversationPagerController(mActivity, this);
    mToastBar = findActionableToastBar(mActivity);
    attachActionBar();

    mDrawIdler.setRootView(mActivity.getWindow().getDecorView());

    final Intent intent = mActivity.getIntent();

    // Immediately handle a clean launch with intent, and any state restoration
    // that does not rely on restored fragments or loader data
    // any state restoration that relies on those can be done later in
    // onRestoreInstanceState, once fragments are up and loader data is re-delivered
    if (savedState != null) {
        //TS: junwei-xu 2015-09-02 EMAIL BUGFIX-546917 ADD-S
        // restore check status for star toggle
        mCheckStatus = savedState.getBoolean(BUNDLE_CHECK_STATUS_KEY, false);
        //TS: junwei-xu 2015-09-02 EMAIL BUGFIX-546917 ADD-E
        /// TCT: restore global search tag.
        if (savedState.containsKey(SAVED_GLOBAL_SEARCH)) {
            mGlobalSearch = savedState.getBoolean(SAVED_GLOBAL_SEARCH);
            LogUtils.logFeature(LogTag.SEARCH_TAG, "onCreate restore mGlobalSearch [%s] ", mGlobalSearch);
        }
        if (savedState.containsKey(SAVED_ACCOUNT)) {
            setAccount((Account) savedState.getParcelable(SAVED_ACCOUNT));
        }
        if (savedState.containsKey(SAVED_FOLDER)) {
            final Folder folder = savedState.getParcelable(SAVED_FOLDER);
            /**
             * TCT: Restore the local search or global search instance:
             * 1. Restore the ConversationListContext from Bundle.
             * 2. Restore query if in global search mode.
             * 3. Update Local Search UI (ActionBarView)
             * @{
             */
            final Bundle bundle = savedState.getParcelable(SAVED_LOCAL_SEARCH);
            if (bundle != null) {
                final ConversationListContext convListContext = ConversationListContext.forBundle(bundle);
                mConvListContext = convListContext;
                LogUtils.logFeature(LogTag.SEARCH_TAG,
                        "onCreate restore ConverationListContext from saved instance [%s] ", mConvListContext);
            }
            String query = mConvListContext != null ? mConvListContext.getSearchQuery() : null;
            if (TextUtils.isEmpty(query) && mGlobalSearch) {
                query = intent.getStringExtra(SearchManager.QUERY);
                mConvListContext.setLocalSearch(true);
                mConvListContext.setSearchQueryText(query);
                LogUtils.logFeature(LogTag.SEARCH_TAG, "onCreate restore global search query [%s]",
                        mConvListContext);
            }
            setListContext(folder, query);
            if (mConvListContext.isLocalSearch()) {
                LogUtils.logFeature(LogTag.SEARCH_TAG, "[Local Search] Enter and execute local search [%s]",
                        query);
                mActionBarController.expandSearch(query, mConvListContext.getSearchField());
            }
            /** @} */
        }
        if (savedState.containsKey(SAVED_ACTION)) {
            mDialogAction = savedState.getInt(SAVED_ACTION);
        }
        mDialogFromSelectedSet = savedState.getBoolean(SAVED_ACTION_FROM_SELECTED, false);
        mViewMode.handleRestore(savedState);
    } else if (intent != null) {
        handleIntent(intent);
    }
    // Create the accounts loader; this loads the account switch spinner.
    mActivity.getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, Bundle.EMPTY, mAccountCallbacks);
    return true;
}

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

/**
 * Starts the global search activity. This code is a copied from SearchManager
 *//*from  w  w w.ja v a  2  s.  com*/
private void startGlobalSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData,
        Rect sourceBounds) {
    final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
    if (globalSearchActivity == null) {
        Log.w(TAG, "No global search activity found.");
        return;
    }
    Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setComponent(globalSearchActivity);
    // Make sure that we have a Bundle to put source in
    if (appSearchData == null) {
        appSearchData = new Bundle();
    } else {
        appSearchData = new Bundle(appSearchData);
    }
    // Set source to package name of app that starts global search if not set already.
    if (!appSearchData.containsKey("source")) {
        appSearchData.putString("source", getPackageName());
    }
    intent.putExtra(SearchManager.APP_DATA, appSearchData);
    if (!TextUtils.isEmpty(initialQuery)) {
        intent.putExtra(SearchManager.QUERY, initialQuery);
    }
    if (selectInitialQuery) {
        intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
    }
    intent.setSourceBounds(sourceBounds);
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException ex) {
        Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
    }
}

From source file:com.dmsl.anyplace.UnifiedNavigationActivity.java

private void handleIntent(Intent intent) {

    String action = intent.getAction();
    if (Intent.ACTION_SEARCH.equals(action)) {

        // check what type of search we need
        SearchTypes searchType = AnyPlaceSeachingHelper.getSearchType(mMap.getCameraPosition().zoom);
        String query = intent.getStringExtra(SearchManager.QUERY);
        GeoPoint gp = userData.getLatestUserPosition();

        // manually launch the real search activity
        Intent searchIntent = new Intent(UnifiedNavigationActivity.this, SearchPOIActivity.class);
        // add query to the Intent Extras
        searchIntent.setAction(action);//from www.  j  a va2  s  .c om
        searchIntent.putExtra("searchType", searchType);
        searchIntent.putExtra("query", query);
        searchIntent.putExtra("lat", (gp == null) ? csLat : gp.dlat);
        searchIntent.putExtra("lng", (gp == null) ? csLon : gp.dlon);
        startActivityForResult(searchIntent, SEARCH_POI_ACTIVITY_RESULT);

    } else if (Intent.ACTION_VIEW.equals(action)) {
        String data = intent.getDataString();

        if (data != null && data.startsWith("http")) {
            final Uri uri = intent.getData();
            if (uri != null) {
                String path = uri.getPath();

                if (path != null && path.equals("/getnavigation")) {
                    String poid = uri.getQueryParameter("poid");
                    if (poid == null || poid.equals("")) {
                        // Share building
                        // http://anyplace.rayzit.com/getnavigation?buid=username_1373876832005&floor=0
                        String buid = uri.getQueryParameter("buid");
                        if (buid == null || buid.equals("")) {
                            Toast.makeText(getBaseContext(), "Buid parameter expected", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            mAutomaticGPSBuildingSelection = false;
                            mAnyplaceCache.loadBuilding(buid, new FetchBuildingTaskListener() {

                                @Override
                                public void onSuccess(String result, final BuildingModel b) {

                                    bypassSelectBuildingActivity(b, uri.getQueryParameter("floor"), true);

                                }

                                @Override
                                public void onErrorOrCancel(String result) {
                                    Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();

                                }
                            }, UnifiedNavigationActivity.this);
                        }
                    } else {
                        // Share POI
                        // http://anyplace.rayzit.com/getnavigation?poid=username_username_1373876832005_0_35.14424091022549_33.41139659285545_1382635428093
                        mAutomaticGPSBuildingSelection = false;
                        new FetchPoiByPuidTask(new FetchPoiByPuidTask.FetchPoiListener() {

                            @Override
                            public void onSuccess(String result, final PoisModel poi) {

                                if (userData.getSelectedBuildingId() != null
                                        && userData.getSelectedBuildingId().equals(poi.buid)) {
                                    // Building is Loaded
                                    startNavigationTask(poi.puid);
                                } else {
                                    // Load Building
                                    mAnyplaceCache.loadBuilding(poi.buid, new FetchBuildingTaskListener() {

                                        @Override
                                        public void onSuccess(String result, final BuildingModel b) {

                                            bypassSelectBuildingActivity(b, poi.floor_number, true, poi);

                                        }

                                        @Override
                                        public void onErrorOrCancel(String result) {
                                            Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();

                                        }
                                    }, UnifiedNavigationActivity.this);
                                }
                            }

                            @Override
                            public void onErrorOrCancel(String result) {
                                Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
                            }
                        }, this, poid).execute();
                    }
                }
            }
        } else {

            // Search TextBox results only

            // PoisModel or Place Class
            IPoisClass place_selected = AnyPlaceSeachingHelper.getClassfromJson(data);

            if (place_selected.id() != null) {
                // hide the search view when a navigation route is drawn
                if (searchView != null) {
                    searchView.setIconified(true);
                    searchView.clearFocus();
                }
                handleSearchPlaceSelection(place_selected);
            }

        }

    }
}

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

/**
 * Starts the global search activity. This code is a copied from SearchManager
 *//*from www  .ja v  a2s.  c om*/
public void startGlobalSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData,
        Rect sourceBounds) {
    final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
    if (globalSearchActivity == null) {
        Log.w(TAG, "No global search activity found.");
        return;
    }
    Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setComponent(globalSearchActivity);
    // Make sure that we have a Bundle to put source in
    if (appSearchData == null) {
        appSearchData = new Bundle();
    } else {
        appSearchData = new Bundle(appSearchData);
    }
    // Set source to package name of app that starts global search if not set already.
    if (!appSearchData.containsKey("source")) {
        appSearchData.putString("source", getPackageName());
    }
    intent.putExtra(SearchManager.APP_DATA, appSearchData);
    if (!TextUtils.isEmpty(initialQuery)) {
        intent.putExtra(SearchManager.QUERY, initialQuery);
    }
    if (selectInitialQuery) {
        intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
    }
    intent.setSourceBounds(sourceBounds);
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException ex) {
        Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
    }
}