Example usage for android.net Uri withAppendedPath

List of usage examples for android.net Uri withAppendedPath

Introduction

In this page you can find the example usage for android.net Uri withAppendedPath.

Prototype

public static Uri withAppendedPath(Uri baseUri, String pathSegment) 

Source Link

Document

Creates a new Uri by appending an already-encoded path segment to a base Uri.

Usage

From source file:com.landenlabs.all_devtool.PackageFragment.java

/**
 * Load packages which are default (associated) with specific mime types.
 *
 * Use "adb shell dumpsys package r" to get full list
 *//* w w w.  j  a  v a  2 s  .c  o m*/
void loadDefaultPackages() {
    m_workList = new ArrayList<PackingItem>();

    String[] actions = { Intent.ACTION_SEND, Intent.ACTION_SEND, Intent.ACTION_SEND, Intent.ACTION_SEND,

            Intent.ACTION_VIEW, Intent.ACTION_VIEW, Intent.ACTION_VIEW, Intent.ACTION_VIEW, Intent.ACTION_VIEW,
            Intent.ACTION_VIEW, Intent.ACTION_VIEW, Intent.ACTION_VIEW,

            MediaStore.ACTION_IMAGE_CAPTURE, MediaStore.ACTION_VIDEO_CAPTURE,

            Intent.ACTION_CREATE_SHORTCUT };

    String[] types = { "audio/*", "video/*", "image/*", "text/plain",

            "application/pdf", "application/zip", "audio/*", "video/*", "image/*", "text/html", "text/plain",
            "text/csv",

            "image/png", "video/*",

            "" };

    long orderCnt = 1;
    for (int idx = 0; idx != actions.length; idx++) {
        String type = types[idx];
        Intent resolveIntent = new Intent(actions[idx]);

        if (!TextUtils.isEmpty(type)) {
            if (type.startsWith("audio/*")) {
                Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
                resolveIntent.setDataAndType(uri, type);
            } else if (type.startsWith("video/*")) {
                Uri uri = Uri.withAppendedPath(MediaStore.Video.Media.INTERNAL_CONTENT_URI, "1");
                resolveIntent.setDataAndType(uri, type);
            } else if (type.startsWith("text/")) {
                Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath());
                resolveIntent.setDataAndType(uri, type);
            } else {
                resolveIntent.setType(type);
            }
        }

        PackageManager pm = getActivity().getPackageManager();

        // PackageManager.GET_RESOLVED_FILTER);  // or PackageManager.MATCH_DEFAULT_ONLY
        List<ResolveInfo> resolveList = pm.queryIntentActivities(resolveIntent, -1); // PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_INTENT_FILTERS);

        if (resolveList != null) {
            String actType = type = Utils.last(actions[idx].split("[.]")) + ":" + type;
            for (ResolveInfo resolveInfo : resolveList) {
                ArrayListPairString pkgList = new ArrayListPairString();
                String appName = resolveInfo.activityInfo.loadLabel(pm).toString().trim();

                addList(pkgList, "Type", actType);
                String pkgName = resolveInfo.activityInfo.packageName;
                PackageInfo packInfo = null;
                try {
                    packInfo = pm.getPackageInfo(pkgName, 0);
                    addList(pkgList, "Version", packInfo.versionName);
                    addList(pkgList, "VerCode", String.valueOf(packInfo.versionCode));
                    addList(pkgList, "TargetSDK", String.valueOf(packInfo.applicationInfo.targetSdkVersion));
                    m_date.setTime(packInfo.firstInstallTime);
                    addList(pkgList, "Install First", s_timeFormat.format(m_date));
                    m_date.setTime(packInfo.lastUpdateTime);
                    addList(pkgList, "Install Last", s_timeFormat.format(m_date));
                    if (resolveInfo.filter != null) {
                        if (resolveInfo.filter.countDataSchemes() > 0) {
                            addList(pkgList, "Intent Scheme", "");
                            for (int sIdx = 0; sIdx != resolveInfo.filter.countDataSchemes(); sIdx++)
                                addList(pkgList, " ", resolveInfo.filter.getDataScheme(sIdx));
                        }
                        if (resolveInfo.filter.countActions() > 0) {
                            addList(pkgList, "Intent Action", "");
                            for (int aIdx = 0; aIdx != resolveInfo.filter.countActions(); aIdx++)
                                addList(pkgList, " ", resolveInfo.filter.getAction(aIdx));
                        }
                        if (resolveInfo.filter.countCategories() > 0) {
                            addList(pkgList, "Intent Category", "");
                            for (int cIdx = 0; cIdx != resolveInfo.filter.countCategories(); cIdx++)
                                addList(pkgList, " ", resolveInfo.filter.getCategory(cIdx));
                        }
                        if (resolveInfo.filter.countDataTypes() > 0) {
                            addList(pkgList, "Intent DataType", "");
                            for (int dIdx = 0; dIdx != resolveInfo.filter.countDataTypes(); dIdx++)
                                addList(pkgList, " ", resolveInfo.filter.getDataType(dIdx));
                        }
                    }
                    m_workList.add(
                            new PackingItem(pkgName.trim(), pkgList, packInfo, orderCnt++, appName, actType));
                } catch (Exception ex) {
                }
            }
        }

        if (false) {
            // TODO - look into this method, see loadCachedPackages
            int flags = PackageManager.GET_PROVIDERS;
            List<PackageInfo> packList = pm.getPreferredPackages(flags);
            if (packList != null) {
                for (int pkgIdx = 0; pkgIdx < packList.size(); pkgIdx++) {
                    PackageInfo packInfo = packList.get(pkgIdx);

                    // if (((packInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) == showSys) {
                    addPackageInfo(packInfo);
                    // }
                }
            }
        }
    }

    // getPreferredAppInfo();

    /*
    List<ProviderInfo> providerList = getActivity().getPackageManager().queryContentProviders(null, 0, 0);
    if (providerList != null) {
    for (ProviderInfo providerInfo : providerList) {
        String name = providerInfo.name;
        String pkg = providerInfo.packageName;
            
    }
    }
    */
}

From source file:org.mariotaku.twidere.util.DataStoreUtils.java

@NonNull
static <T> T getFieldArray(@NonNull Context context, @NonNull Uri uri, @NonNull UserKey[] keys,
        @NonNull String keyField, @NonNull String valueField, @Nullable OrderBy sortExpression,
        @NonNull FieldArrayCreator<T> creator) {
    final ContentResolver resolver = context.getContentResolver();
    final T messageIds = creator.newArray(keys.length);
    final String[] selectionArgs = TwidereArrayUtils.toStringArray(keys);
    final SQLSelectQuery.Builder builder = SQLQueryBuilder.select(new Columns(keyField, valueField))
            .from(new Table(getTableNameByUri(uri))).groupBy(new Column(keyField))
            .having(Expression.in(new Column(keyField), new ArgsArray(keys.length)));
    if (sortExpression != null) {
        builder.orderBy(sortExpression);
    }//from w  ww.  jav a2 s .  c  om
    final Cursor cur = resolver.query(
            Uri.withAppendedPath(TwidereDataStore.CONTENT_URI_RAW_QUERY, builder.buildSQL()), null, null,
            selectionArgs, null);
    if (cur == null)
        return messageIds;
    try {
        while (cur.moveToNext()) {
            final UserKey accountKey = UserKey.valueOf(cur.getString(0));
            int idx = ArrayUtils.indexOf(keys, accountKey);
            if (idx < 0)
                continue;
            creator.assign(messageIds, idx, cur, 1);
        }
        return messageIds;
    } finally {
        cur.close();
    }
}

From source file:cx.ring.service.LocalService.java

public void updateTextNotifications() {
    Log.d(TAG, "updateTextNotifications()");

    for (Conversation c : conversations.values()) {
        TreeMap<Long, TextMessage> texts = c.getUnreadTextMessages();
        if (texts.isEmpty() || texts.lastEntry().getValue().isNotified()) {
            continue;
        } else/*from w w w.  j a v a  2 s  .  c o m*/
            notificationManager.cancel(c.notificationId);

        CallContact contact = c.getContact();
        if (c.notificationBuilder == null) {
            c.notificationBuilder = new NotificationCompat.Builder(getApplicationContext());
            c.notificationBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setPriority(NotificationCompat.PRIORITY_HIGH).setDefaults(NotificationCompat.DEFAULT_ALL)
                    .setSmallIcon(R.drawable.ic_launcher).setContentTitle(contact.getDisplayName());
        }
        NotificationCompat.Builder noti = c.notificationBuilder;
        Intent c_intent = new Intent(Intent.ACTION_VIEW).setClass(this, ConversationActivity.class)
                .setData(Uri.withAppendedPath(ConversationActivity.CONTENT_URI, contact.getIds().get(0)));
        Intent d_intent = new Intent(ACTION_CONV_READ).setClass(this, LocalService.class)
                .setData(Uri.withAppendedPath(ConversationActivity.CONTENT_URI, contact.getIds().get(0)));
        noti.setContentIntent(PendingIntent.getActivity(this, new Random().nextInt(), c_intent, 0))
                .setDeleteIntent(PendingIntent.getService(this, new Random().nextInt(), d_intent, 0));

        if (contact.getPhoto() != null) {
            Resources res = getResources();
            int height = (int) res.getDimension(android.R.dimen.notification_large_icon_height);
            int width = (int) res.getDimension(android.R.dimen.notification_large_icon_width);
            noti.setLargeIcon(Bitmap.createScaledBitmap(contact.getPhoto(), width, height, false));
        }
        if (texts.size() == 1) {
            TextMessage txt = texts.firstEntry().getValue();
            txt.setNotified(true);
            noti.setContentText(txt.getMessage());
            noti.setStyle(null);
            noti.setWhen(txt.getTimestamp());
        } else {
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            for (TextMessage s : texts.values()) {
                inboxStyle.addLine(Html.fromHtml("<b>"
                        + DateUtils.formatDateTime(this, s.getTimestamp(),
                                DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL)
                        + "</b> " + s.getMessage()));
                s.setNotified(true);
            }
            noti.setContentText(texts.lastEntry().getValue().getMessage());
            noti.setStyle(inboxStyle);
            noti.setWhen(texts.lastEntry().getValue().getTimestamp());
        }
        notificationManager.notify(c.notificationId, noti.build());
    }
}

From source file:org.kontalk.ui.AbstractComposeFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // image from storage/picture from camera
    // since there are like up to 3 different ways of doing this...
    if (requestCode == SELECT_ATTACHMENT_OPENABLE || requestCode == SELECT_ATTACHMENT_PHOTO) {
        if (resultCode == Activity.RESULT_OK) {
            Uri[] uris = null;/* www .j  a v a 2 s  .  c  o m*/
            String[] mimes = null;

            // returning from camera
            if (requestCode == SELECT_ATTACHMENT_PHOTO) {
                if (mCurrentPhoto != null) {
                    Uri uri = Uri.fromFile(mCurrentPhoto);
                    // notify media scanner
                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    mediaScanIntent.setData(uri);
                    getActivity().sendBroadcast(mediaScanIntent);
                    mCurrentPhoto = null;

                    uris = new Uri[] { uri };
                }
            } else {
                if (mCurrentPhoto != null) {
                    mCurrentPhoto.delete();
                    mCurrentPhoto = null;
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && data.getClipData() != null) {
                    ClipData cdata = data.getClipData();
                    uris = new Uri[cdata.getItemCount()];

                    for (int i = 0; i < uris.length; i++) {
                        ClipData.Item item = cdata.getItemAt(i);
                        uris[i] = item.getUri();
                    }
                } else {
                    uris = new Uri[] { data.getData() };
                    mimes = new String[] { data.getType() };
                }

                // SAF available, request persistable permissions
                if (MediaStorage.isStorageAccessFrameworkAvailable()) {
                    for (Uri uri : uris) {
                        if (uri != null && !"file".equals(uri.getScheme())) {
                            MediaStorage.requestPersistablePermissions(getActivity(), uri);
                        }
                    }
                }
            }

            for (int i = 0; uris != null && i < uris.length; i++) {
                Uri uri = uris[i];
                if (uri == null)
                    continue;

                String mime = (mimes != null && mimes.length >= uris.length) ? mimes[i] : null;

                if (mime == null || mime.startsWith("*/") || mime.endsWith("/*")) {
                    mime = MediaStorage.getType(getActivity(), uri);
                    Log.v(TAG, "using detected mime type " + mime);
                }

                if (ImageComponent.supportsMimeType(mime))
                    sendBinaryMessage(uri, mime, true, ImageComponent.class);
                else if (VCardComponent.supportsMimeType(mime))
                    sendBinaryMessage(uri, VCardComponent.MIME_TYPE, false, VCardComponent.class);
                else
                    Toast.makeText(getActivity(), R.string.send_mime_not_supported, Toast.LENGTH_LONG).show();
            }
        }
        // operation aborted
        else {
            // delete photo :)
            if (mCurrentPhoto != null) {
                mCurrentPhoto.delete();
                mCurrentPhoto = null;
            }
        }
    }
    // contact card (vCard)
    else if (requestCode == SELECT_ATTACHMENT_CONTACT) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                Uri vcardUri = null;

                // get lookup key
                final Cursor c = getContext().getContentResolver().query(uri,
                        new String[] { Contacts.LOOKUP_KEY }, null, null, null);
                if (c != null) {
                    try {
                        if (c.moveToFirst()) {
                            String lookupKey = c.getString(0);
                            vcardUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);
                        }
                    } catch (Exception e) {
                        Log.w(TAG, "unable to lookup selected contact. Did you grant me the permission?", e);
                        ReportingManager.logException(e);
                    } finally {
                        c.close();
                    }
                }

                if (vcardUri != null) {
                    sendBinaryMessage(vcardUri, VCardComponent.MIME_TYPE, false, VCardComponent.class);
                } else {
                    Toast.makeText(getContext(), R.string.err_no_contact, Toast.LENGTH_LONG).show();
                }
            }
        }
    }
    // invite user
    else if (requestCode == REQUEST_INVITE_USERS) {
        if (resultCode == Activity.RESULT_OK) {

            ArrayList<Uri> uris;
            Uri threadUri = data.getData();
            if (threadUri != null) {
                String userId = threadUri.getLastPathSegment();
                addUsers(new String[] { userId });
            } else if ((uris = data.getParcelableArrayListExtra("org.kontalk.contacts")) != null) {
                String[] users = new String[uris.size()];
                for (int i = 0; i < users.length; i++)
                    users[i] = uris.get(i).getLastPathSegment();
                addUsers(users);
            }

        }
    }
}

From source file:com.android.bluetooth.map.BluetoothMapContent.java

private String getContactNameFromPhone(String phone) {
    String name = "";
    if (TextUtils.isEmpty(phone)) {
        return name;
    }/*from   w  w  w .  j  a v a  2s . co m*/
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));

    String[] projection = { Contacts._ID, Contacts.DISPLAY_NAME };
    String selection = Contacts.IN_VISIBLE_GROUP + "=1";
    String orderBy = Contacts.DISPLAY_NAME + " ASC";

    Cursor c = mResolver.query(uri, projection, selection, null, orderBy);
    try {
        if (c != null && c.getCount() >= 1) {
            c.moveToFirst();
            name = c.getString(c.getColumnIndex(Contacts.DISPLAY_NAME));
        }
        ;
    } finally {
        close(c);
    }
    return name;
}

From source file:com.nononsenseapps.notepad.MainActivity.java

@Override
public void onItemSelected(long id) {
    Log.d(TAG, "onItemSelected: " + id);
    // Open a note
    if (id > -1) {
        if (getCurrentContent().equals(DualLayoutActivity.CONTENTVIEW.DUAL)) {
            Bundle arguments = new Bundle();
            arguments.putLong(NotesEditorFragment.KEYID, id);
            NotesEditorFragment fragment = new NotesEditorFragment();
            fragment.setArguments(arguments);
            getFragmentManager().beginTransaction().replace(R.id.rightFragment, fragment)
                    .commitAllowingStateLoss();
        } else {/*from  w ww  . j a  v  a2 s .  c  om*/
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setClass(this, RightActivity.class)
                    .setData(Uri.withAppendedPath(NotePad.Notes.CONTENT_VISIBLE_ID_URI_BASE, Long.toString(id)))
                    .setAction(Intent.ACTION_EDIT);

            startActivity(intent);
        }
    }
}

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

protected void savePhoto(long person, InputStream photoInput, String photoVersion) throws IOException {
    try {/*www . j  a  v a 2s  .  c  o  m*/
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        while (true) {
            int bytesRead = photoInput.read(data);
            if (bytesRead < 0)
                break;
            byteStream.write(data, 0, bytesRead);
        }

        ContentValues values = new ContentValues();
        // we have to include this here otherwise the provider will set it to 1
        values.put(Photos._SYNC_DIRTY, 0);
        values.put(Photos.LOCAL_VERSION, photoVersion);
        values.put(Photos.DATA, byteStream.toByteArray());
        Uri photoUri = Uri.withAppendedPath(People.CONTENT_URI, "" + person + "/" + Photos.CONTENT_DIRECTORY);
        if (getContext().getContentResolver().update(photoUri, values, "_sync_dirty=0", null) > 0) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "savePhoto: updated " + photoUri + " with values " + values);
            }
        } else {
            Log.e(TAG, "savePhoto: update of " + photoUri + " with values " + values + " affected no rows");
        }
    } finally {
        try {
            if (photoInput != null)
                photoInput.close();
        } catch (IOException e) {
            // we don't care about exceptions here
        }
    }
}

From source file:org.opendatakit.survey.activities.MainMenuActivity.java

public void swapToFragmentView(ScreenList newScreenType) {
    WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView: " + newScreenType.name());
    FragmentManager mgr = getFragmentManager();
    FragmentTransaction trans = null;/*ww  w  .j ava 2 s .com*/
    Fragment newFragment = null;
    if (newScreenType == ScreenList.MAIN_SCREEN) {
        throw new IllegalStateException("unexpected reference to generic main screen");
    } else if (newScreenType == ScreenList.FORM_CHOOSER) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new FormChooserListFragment();
        }
    } else if (newScreenType == ScreenList.FRONT_PAGE) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new FrontPageFragment();
        }
    } else if (newScreenType == ScreenList.INITIALIZATION_DIALOG) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new InitializationFragment();
        }
    } else if (newScreenType == ScreenList.WEBKIT) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            WebLogger.getLogger(getAppName()).i(t,
                    "[" + this.hashCode() + "] creating new webkit fragment " + newScreenType.name());
            newFragment = new WebViewFragment();
        }
    } else if (newScreenType == ScreenList.ABOUT_MENU) {
        newFragment = mgr.findFragmentByTag(newScreenType.name());
        if (newFragment == null) {
            newFragment = new AboutMenuFragment();
        }

    } else {
        throw new IllegalStateException("Unrecognized ScreenList type");
    }

    boolean matchingBackStackEntry = false;
    for (int i = 0; i < mgr.getBackStackEntryCount(); ++i) {
        BackStackEntry e = mgr.getBackStackEntryAt(i);
        WebLogger.getLogger(getAppName()).i(t, "BackStackEntry[" + i + "] " + e.getName());
        if (e.getName().equals(newScreenType.name())) {
            matchingBackStackEntry = true;
        }
    }

    if (matchingBackStackEntry) {
        if (trans != null) {
            WebLogger.getLogger(getAppName()).e(t, "Unexpected active transaction when popping state!");
            trans = null;
        }
        // flush backward, to the screen we want to go back to
        currentFragment = newScreenType;
        WebLogger.getLogger(getAppName()).e(t,
                "[" + this.hashCode() + "] popping back stack " + currentFragment.name());
        mgr.popBackStackImmediate(currentFragment.name(), 0);
    } else {
        // add transaction to show the screen we want
        if (trans == null) {
            trans = mgr.beginTransaction();
        }
        currentFragment = newScreenType;
        trans.replace(R.id.main_content, newFragment, currentFragment.name());
        WebLogger.getLogger(getAppName()).i(t,
                "[" + this.hashCode() + "] adding to back stack " + currentFragment.name());
        trans.addToBackStack(currentFragment.name());
    }

    // and see if we should re-initialize...
    if ((currentFragment != ScreenList.INITIALIZATION_DIALOG)
            && ((Survey) getApplication()).shouldRunInitializationTask(getAppName())) {
        WebLogger.getLogger(getAppName()).i(t, "swapToFragmentView -- calling clearRunInitializationTask");
        // and immediately clear the should-run flag...
        ((Survey) getApplication()).clearRunInitializationTask(getAppName());
        // OK we should swap to the InitializationFragment view
        // this will skip the transition to whatever screen we were trying to 
        // go to and will instead show the InitializationFragment view. We
        // restore to the desired screen via the setFragmentToShowNext()
        //
        // NOTE: this discards the uncommitted transaction.
        // Robolectric complains about a recursive state transition.
        if (trans != null) {
            trans.commit();
        }
        swapToFragmentView(ScreenList.INITIALIZATION_DIALOG);
    } else {
        // before we actually switch to a WebKit, be sure
        // we have the form definition for it...
        if (currentFragment == ScreenList.WEBKIT && getCurrentForm() == null) {
            // we were sent off to the initialization dialog to try to
            // discover the form. We need to inquire about the form again
            // and, if we cannot find it, report an error to the user.
            final Uri uriFormsProvider = FormsProviderAPI.CONTENT_URI;
            Uri uri = getIntent().getData();
            Uri formUri = null;

            if (uri.getScheme().equalsIgnoreCase(uriFormsProvider.getScheme())
                    && uri.getAuthority().equalsIgnoreCase(uriFormsProvider.getAuthority())) {
                List<String> segments = uri.getPathSegments();
                if (segments != null && segments.size() >= 2) {
                    String appName = segments.get(0);
                    setAppName(appName);
                    String tableId = segments.get(1);
                    String formId = (segments.size() > 2) ? segments.get(2) : null;
                    formUri = Uri.withAppendedPath(Uri.withAppendedPath(
                            Uri.withAppendedPath(FormsProviderAPI.CONTENT_URI, appName), tableId), formId);
                } else {
                    swapToFragmentView(ScreenList.FRONT_PAGE);
                    createErrorDialog(getString(R.string.invalid_uri_expecting_n_segments, uri.toString(), 2),
                            EXIT);
                    return;
                }
                // request specifies a specific formUri -- try to open that
                FormIdStruct newForm = FormIdStruct.retrieveFormIdStruct(getContentResolver(), formUri);
                if (newForm == null) {
                    // error
                    swapToFragmentView(ScreenList.FRONT_PAGE);
                    createErrorDialog(getString(R.string.form_not_found, segments.get(1)), EXIT);
                    return;
                } else {
                    transitionToFormHelper(uri, newForm);
                }
            }
        }

        if (trans != null) {
            trans.commit();
        }
        invalidateOptionsMenu();
    }
}

From source file:com.android.contacts.activities.PeopleActivity.java

/**
 * Share all contacts that are currently selected in mAllFragment. This method is pretty
 * inefficient for handling large numbers of contacts. I don't expect this to be a problem.
 *///from   w w w.  j a va 2s  . com
private void shareSelectedContacts() {
    final StringBuilder uriListBuilder = new StringBuilder();
    for (Long contactId : mAllFragment.getSelectedContactIds()) {
        final Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
        final Uri lookupUri = Contacts.getLookupUri(getContentResolver(), contactUri);
        if (lookupUri == null) {
            continue;
        }
        final List<String> pathSegments = lookupUri.getPathSegments();
        if (pathSegments.size() < 2) {
            continue;
        }
        final String lookupKey = pathSegments.get(pathSegments.size() - 2);
        if (uriListBuilder.length() > 0) {
            uriListBuilder.append(':');
        }
        uriListBuilder.append(Uri.encode(lookupKey));
    }
    if (uriListBuilder.length() == 0) {
        return;
    }
    final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_MULTI_VCARD_URI,
            Uri.encode(uriListBuilder.toString()));
    final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType(Contacts.CONTENT_VCARD_TYPE);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    ImplicitIntentsUtil.startActivityOutsideApp(this, intent);
}

From source file:org.linphone.ContactsManager.java

public Contact findContactWithAddress(ContentResolver contentResolver, LinphoneAddress address) {
    String sipUri = address.asStringUriOnly();
    if (sipUri.startsWith("sip:"))
        sipUri = sipUri.substring(4);//from  w  ww .j  a  v  a2 s  .  c o  m

    LinphoneCore lc = LinphoneManager.getLcIfManagerNotDestroyedOrNull();
    if (lc != null && lc.getFriendList() != null
            && LinphoneManager.getLcIfManagerNotDestroyedOrNull().getFriendList().length > 0) {
        for (LinphoneFriend friend : LinphoneManager.getLcIfManagerNotDestroyedOrNull().getFriendList()) {
            if (friend.getAddress().equals(address)) {
                return getContact(friend.getRefKey(), contentResolver);
            }
        }
    }

    //Find Sip address
    Contact contact;
    String[] projection = new String[] { ContactsContract.Data.CONTACT_ID, ContactsContract.Data.DISPLAY_NAME };
    String selection = new StringBuilder().append(ContactsContract.CommonDataKinds.SipAddress.SIP_ADDRESS)
            .append(" = ?").toString();

    Cursor cur = contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, selection,
            new String[] { sipUri }, null);
    if (cur != null) {
        if (cur.moveToFirst()) {
            contact = Compatibility.getContact(contentResolver, cur, cur.getPosition());
            cur.close();

            if (contact != null) {
                return contact;
            }
        }
        cur.close();
    }

    //Find number
    Uri lookupUri = Uri.withAppendedPath(android.provider.ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(address.getUserName()));
    projection = new String[] { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER,
            ContactsContract.PhoneLookup.DISPLAY_NAME };
    Cursor c = contentResolver.query(lookupUri, projection, null, null, null);
    contact = checkPhoneQueryResult(contentResolver, c, ContactsContract.PhoneLookup.NUMBER,
            ContactsContract.PhoneLookup._ID, address.getUserName());

    if (contact != null) {
        return contact;
    }

    return null;
}