Example usage for android.provider ContactsContract AUTHORITY

List of usage examples for android.provider ContactsContract AUTHORITY

Introduction

In this page you can find the example usage for android.provider ContactsContract AUTHORITY.

Prototype

String AUTHORITY

To view the source code for android.provider ContactsContract AUTHORITY.

Click Source Link

Document

The authority for the contacts provider

Usage

From source file:org.sufficientlysecure.keychain.service.ContactSyncAdapterService.java

public static void enableContactsSync(Context context) {
    Account account = KeychainApplication.createAccountIfNecessary(context);
    if (account == null) {
        return;/*w  ww  .java 2s  .  co m*/
    }

    ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
    ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
}

From source file:cn.pjt.rxjava.contacts.ContactsFragment.java

/**
 * Accesses the Contacts content provider directly to insert a new contact.
 * <p>/*from   ww  w . j  a  v  a 2  s  .c  o m*/
 * The contact is called "__DUMMY ENTRY" and only contains a name.
 */
private void insertDummyContact() {
    // Two operations are needed to insert a new contact.
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(2);

    // First, set up a new raw contact.
    ContentProviderOperation.Builder op = ContentProviderOperation
            .newInsert(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null);
    operations.add(op.build());

    // Next, set the name for the contact.
    op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DUMMY_CONTACT_NAME);
    operations.add(op.build());

    // Apply the operations.
    ContentResolver resolver = getActivity().getContentResolver();
    try {
        resolver.applyBatch(ContactsContract.AUTHORITY, operations);
    } catch (RemoteException e) {
        Log.d(TAG, "Could not add a new contact: " + e.getMessage());
    } catch (OperationApplicationException e) {
        Log.d(TAG, "Could not add a new contact: " + e.getMessage());
    }
}

From source file:org.linphone.ContactEditorFragment.java

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    this.inflater = inflater;

    contact = null;// w  ww.ja v a  2 s.co  m
    if (getArguments() != null) {
        if (getArguments().getSerializable("Contact") != null) {
            contact = (Contact) getArguments().getSerializable("Contact");
            isNewContact = false;
            contactID = Integer.parseInt(contact.getID());
            contact.refresh(getActivity().getContentResolver());
            if (getArguments().getString("NewSipAdress") != null) {
                newSipOrNumberToAdd = getArguments().getString("NewSipAdress");
            }

        } else if (getArguments().getString("NewSipAdress") != null) {
            newSipOrNumberToAdd = getArguments().getString("NewSipAdress");
            isNewContact = true;
        }
    }

    contactsManager = ContactsManager.getInstance();

    view = inflater.inflate(R.layout.contact_edit, container, false);

    deleteContact = (ImageView) view.findViewById(R.id.delete_contact);

    cancel = (ImageView) view.findViewById(R.id.cancel);
    cancel.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().popBackStackImmediate();
        }
    });

    ok = (ImageView) view.findViewById(R.id.ok);
    ok.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isNewContact) {
                boolean areAllFielsEmpty = true;
                for (NewOrUpdatedNumberOrAddress nounoa : numbersAndAddresses) {
                    if (nounoa.newNumberOrAddress != null && !nounoa.newNumberOrAddress.equals("")) {
                        areAllFielsEmpty = false;
                        break;
                    }
                }
                if (areAllFielsEmpty) {
                    getFragmentManager().popBackStackImmediate();
                    return;
                }
                contactsManager.createNewContact(ops, firstName.getText().toString(),
                        lastName.getText().toString());
                setContactPhoto();
            } else {
                contactsManager.updateExistingContact(ops, contact, firstName.getText().toString(),
                        lastName.getText().toString());
                setContactPhoto();
            }

            for (NewOrUpdatedNumberOrAddress numberOrAddress : numbersAndAddresses) {
                numberOrAddress.save();
            }

            try {
                getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                addLinphoneFriendIfNeeded();
                removeLinphoneTagIfNeeded();
                contactsManager.prepareContactsInBackground();
            } catch (Exception e) {
                e.printStackTrace();
            }

            getFragmentManager().popBackStackImmediate();

            if (LinphoneActivity.instance().getResources().getBoolean(R.bool.isTablet))
                ContactsListFragment.instance().invalidate();
        }
    });

    lastName = (EditText) view.findViewById(R.id.contactLastName);
    // Hack to display keyboard when touching focused edittext on Nexus One
    if (Version.sdkStrictlyBelow(Version.API11_HONEYCOMB_30)) {
        lastName.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) LinphoneActivity.instance()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            }
        });
    }
    lastName.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (lastName.getText().length() > 0 || firstName.getText().length() > 0) {
                ok.setEnabled(true);
            } else {
                ok.setEnabled(false);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    firstName = (EditText) view.findViewById(R.id.contactFirstName);
    firstName.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (firstName.getText().length() > 0 || lastName.getText().length() > 0) {
                ok.setEnabled(true);
            } else {
                ok.setEnabled(false);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    if (!isNewContact) {
        String fn = findContactFirstName(String.valueOf(contactID));
        String ln = findContactLastName(String.valueOf(contactID));
        if (fn != null || ln != null) {
            firstName.setText(fn);
            lastName.setText(ln);
        } else {
            lastName.setText(contact.getName());
            firstName.setText("");
        }
        deleteContact.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                final Dialog dialog = LinphoneActivity.instance()
                        .displayDialog(getString(R.string.delete_text));
                Button delete = (Button) dialog.findViewById(R.id.delete_button);
                Button cancel = (Button) dialog.findViewById(R.id.cancel);

                delete.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        deleteExistingContact();
                        ContactsManager.getInstance().removeContactFromLists(getActivity().getContentResolver(),
                                contact);
                        LinphoneActivity.instance().displayContacts(false);
                        dialog.dismiss();
                    }
                });

                cancel.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();

                    }
                });
                dialog.show();
            }
        });
    } else {
        deleteContact.setVisibility(View.INVISIBLE);
    }

    contactPicture = (ImageView) view.findViewById(R.id.contact_picture);
    if (contact != null && contact.getPhotoUri() != null) {
        InputStream input = Compatibility.getContactPictureInputStream(getActivity().getContentResolver(),
                contact.getID());
        contactPicture.setImageBitmap(BitmapFactory.decodeStream(input));
    } else {
        contactPicture.setImageResource(R.drawable.avatar);
    }

    contactPicture.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            pickImage();
        }
    });

    numbersAndAddresses = new ArrayList<NewOrUpdatedNumberOrAddress>();
    sipAddresses = initSipAddressFields(contact);
    numbers = initNumbersFields(contact);

    addSipAddress = (ImageView) view.findViewById(R.id.add_address_field);
    addSipAddress.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            addEmptyRowToAllowNewNumberOrAddress(sipAddresses, true);
        }
    });

    addNumber = (ImageView) view.findViewById(R.id.add_number_field);
    addNumber.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            addEmptyRowToAllowNewNumberOrAddress(numbers, false);
        }
    });

    ops = new ArrayList<ContentProviderOperation>();
    lastName.requestFocus();

    return view;
}

From source file:org.sufficientlysecure.keychain.service.ContactSyncAdapterService.java

public static void deleteIfSyncDisabled(Context context) {
    if (!(ContextCompat.checkSelfPermission(context,
            Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)) {
        return;/* w ww . j  a  v a  2s .co m*/
    }

    Account account = KeychainApplication.createAccountIfNecessary(context);
    if (account == null) {
        return;
    }

    // if user has disabled automatic sync, delete linked OpenKeychain contacts
    if (!ContentResolver.getSyncAutomatically(account, ContactsContract.AUTHORITY)) {
        new ContactHelper(context).deleteAllContacts();
    }
}

From source file:uk.co.bubblebearapps.contactsintegration.MainActivity.java

private void syncAccount(Account account) {

    // Pass the settings flags by inserting them in a bundle
    Bundle settingsBundle = new Bundle();
    settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    /*/* w  w w .  j  av  a  2s  .c  om*/
     * Request the sync for the default account, authority, and
     * manual sync settings
     */
    ContentResolver.requestSync(account, ContactsContract.AUTHORITY, settingsBundle);

    showMessage("Sync requested, view results in Contacts app");

}

From source file:org.codarama.haxsync.services.ContactsSyncAdapterService.java

private static void addSelfContact(Account account, int maxSize, boolean square, boolean faceDetect,
        boolean force, boolean root, int rootsize, File cacheDir, boolean google) {

    Uri rawContactUri = ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI.buildUpon()
            .appendQueryParameter(RawContacts.ACCOUNT_NAME, account.name)
            .appendQueryParameter(RawContacts.ACCOUNT_TYPE, account.type).build();

    long ID = -2;
    String username;/* w  w w . j a  v  a2 s  .  c om*/
    String email;
    FacebookGraphFriend user = FacebookUtil.getSelfInfo();
    if (user == null)
        return;
    Cursor cursor = mContentResolver.query(rawContactUri, new String[] { BaseColumns._ID, UsernameColumn },
            null, null, null);
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        ID = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        username = cursor.getString(cursor.getColumnIndex(UsernameColumn));
        cursor.close();
    } else {
        cursor.close();
        username = user.getUserName();
        email = user.getEmail();

        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();

        ContentProviderOperation.Builder builder = ContentProviderOperation
                .newInsert(ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI);
        builder.withValue(RawContacts.ACCOUNT_NAME, account.name);
        builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);
        builder.withValue(RawContacts.SYNC1, username);
        operationList.add(builder.build());

        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, account.name);
        operationList.add(builder.build());

        builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
        builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
        builder.withValue(ContactsContract.Data.MIMETYPE,
                "vnd.android.cursor.item/vnd.org.codarama.haxsync.profile");
        builder.withValue(ContactsContract.Data.DATA1, username);
        builder.withValue(ContactsContract.Data.DATA2, "Facebook Profile");
        builder.withValue(ContactsContract.Data.DATA3, "View profile");
        operationList.add(builder.build());

        if (email != null) {
            builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
            builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
            builder.withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            builder.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
            operationList.add(builder.build());
        }

        try {
            mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList);
        } catch (Exception e) {
            // FIXME catching generic Exception class is not the best thing to do
            Log.e("Error", e.getLocalizedMessage());
            return;
        }
        cursor = mContentResolver.query(rawContactUri, new String[] { BaseColumns._ID }, null, null, null);
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            ID = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
            cursor.close();
        } else {
            Log.i(TAG, "NO SELF CONTACT FOUND");
            return;
        }
    }
    Log.i("self contact", "id: " + ID + " uid: " + username);
    if (ID != -2 && username != null) {

        updateContactPhoto(ID, 0, maxSize, square, user.getPicURL(), faceDetect, true, root, rootsize, cacheDir,
                google, true);

    }
}

From source file:com.android.contacts.database.SimContactDaoImpl.java

private ContentProviderResult[] importBatch(List<SimContact> contacts, AccountWithDataSet targetAccount)
        throws RemoteException, OperationApplicationException {
    final ArrayList<ContentProviderOperation> ops = createImportOperations(contacts, targetAccount);
    return mResolver.applyBatch(ContactsContract.AUTHORITY, ops);
}

From source file:pt.up.mobile.authenticator.AuthenticatorActivity.java

/**
 * Called when response is received from the server for authentication
 * request. See onAuthenticationResult(). Sets the
 * AccountAuthenticatorResult which is sent back to the caller. We store the
 * authToken that's returned from the server as the 'password' for this
 * account - so we're never storing the user's actual password locally.
 * /*from   w w  w  .  j  a  v a2  s.co m*/
 * @param result
 *            the confirmCredentials result.
 */
@TargetApi(8)
private void finishLogin(final User user) {

    Log.i(TAG, "finishLogin()");
    new Thread(new Runnable() {
        @Override
        public void run() {
            final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);
            if (mRequestNewAccount) {
                final ContentValues values = new ContentValues();
                values.put(SigarraContract.Users.CODE, user.getUserCode());
                values.put(SigarraContract.Users.TYPE, user.getType());
                values.put(SigarraContract.Users.ID, account.name);
                getContentResolver().insert(SigarraContract.Users.CONTENT_URI, values);
                // Set contacts sync for this account.

                if (!mAccountManager.addAccountExplicitly(account, mPassword, Bundle.EMPTY)) {
                    getContentResolver().delete(SigarraContract.Users.CONTENT_URI,
                            SigarraContract.Users.PROFILE,
                            SigarraContract.Users.getUserSelectionArgs(account.name));
                    finish();
                }
                String syncIntervalValue = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext())
                        .getString(getString(R.string.key_sync_interval),
                                Integer.toString(getResources().getInteger(R.integer.default_sync_interval)));

                String syncNotIntervalValue = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext())
                        .getString(getString(R.string.key_notifications_sync_interval),
                                Integer.toString(getResources().getInteger(R.integer.default_sync_interval)));

                ContentResolver.setSyncAutomatically(account, SigarraContract.CONTENT_AUTHORITY, true);
                ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                    ContentResolver.addPeriodicSync(account, SigarraContract.CONTENT_AUTHORITY, Bundle.EMPTY,
                            Integer.parseInt(syncIntervalValue) * 3600);
                    ContentResolver.addPeriodicSync(account, SigarraContract.CONTENT_AUTHORITY,
                            SigarraSyncAdapterUtils.getNotificationsPeriodicBundle(),
                            Integer.parseInt(syncNotIntervalValue) * 3600);
                } else {
                    PeriodicSyncReceiver.cancelPreviousAlarms(getApplicationContext(), account,
                            SigarraContract.CONTENT_AUTHORITY, Bundle.EMPTY);
                    PeriodicSyncReceiver.addPeriodicSync(getApplicationContext(), account,
                            SigarraContract.CONTENT_AUTHORITY, Bundle.EMPTY,
                            Integer.parseInt(syncIntervalValue) * 3600);

                    PeriodicSyncReceiver.addPeriodicSync(getApplicationContext(), account,
                            SigarraContract.CONTENT_AUTHORITY, SigarraSyncAdapterUtils.getNotificationsBundle(),
                            Integer.parseInt(syncNotIntervalValue) * 3600);
                }
            } else {
                mAccountManager.setPassword(account, user.getPassword());
            }
            final Intent intent = new Intent();
            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
            setAccountAuthenticatorResult(intent.getExtras());
            setResult(RESULT_OK, intent);
            finish();
        }
    }).start();
}

From source file:com.barak.pix.FeedsActivity.java

/**
 * This method add my account under IM field at default Contact
 * application/*from  w ww.j  av  a2s . c  o m*/
 *
 * Labeled with my custom protocol.
 *
 * @param contentResolver
 *            content resolver
 * @param uid
 *            User id from android
 * @param account
 *            account name
 */
public static void updateIMContactField(ContentResolver contentResolver, String uid, String account) {

    ContentValues contentValues = new ContentValues();

    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, Integer.parseInt(uid));
    contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
    contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE,
            ContactsContract.CommonDataKinds.Im.TYPE_CUSTOM);
    contentValues.put(ContactsContract.CommonDataKinds.Im.LABEL, IM_LABEL);
    contentValues.put(ContactsContract.CommonDataKinds.Im.PROTOCOL,
            ContactsContract.CommonDataKinds.Im.PROTOCOL_CUSTOM);
    contentValues.put(ContactsContract.CommonDataKinds.Im.CUSTOM_PROTOCOL, IM_LABEL);

    contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, account);

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues)
            .build());

    try {
        contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        Log.d(LOG_TAG, "Can't update Contact's IM field.");
    }
}

From source file:com.nbos.phonebook.sync.authenticator.AuthenticatorActivity.java

/**
 * //from  www .  ja  v a 2s  .  c o m
 * Called when response is received from the server for authentication
 * request. See onAuthenticationResult(). Sets the
 * AccountAuthenticatorResult which is sent back to the caller. Also sets
 * the authToken in AccountManager for this account.
 * 
 * @param the confirmCredentials result.
 */

protected void finishLogin() {
    Log.i(tag, "finishLogin()");
    final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);
        mAccountManager.setUserData(account, Constants.PHONE_NUMBER_KEY, countryCode + mPhone);
        // Set contacts sync for this account.
        ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    mAuthtoken = mPassword;
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
    if (mAuthtokenType != null && mAuthtokenType.equals(Constants.AUTHTOKEN_TYPE))
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
    Db.deleteServerData(getApplicationContext());
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}