Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Class for managing contacts sync related operations
- */
- public class ContactsManager {
- /**
- * tag string for LogCat
- */
- private static final String TAG = ContactsManager.class.toString();
- ...
- /**
- * Retrieve all phone numbers from the android contacts
- * @return ArrayList of strings, where each string is a phone number
- */
- public static synchronized Collection<String> getPhones(Context context) {
- Collection<String> result = new ArrayList<>();
- ContentResolver cr = context.getContentResolver();
- Cursor pCur = cr.query(
- ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
- null, null, null, null);
- while (pCur.moveToNext()) {
- String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
- phoneNo = phoneNo.replace(" ", "");
- phoneNo = phoneNo.replace("-", "");
- if (phoneNo.charAt(0) != '+') { // phone number has a country code
- if (!Character.isDigit(phoneNo.charAt(0)))
- continue;
- String iso = getUserCountry(context);
- PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
- try { // adding country code
- Phonenumber.PhoneNumber localNumber = phoneUtil.parse(phoneNo, iso);
- if (!phoneUtil.isPossibleNumber(localNumber))
- continue;
- phoneNo = phoneUtil.format(localNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
- } catch (NumberParseException e) {
- System.err.println("NumberParseException: " + e.toString());
- }
- }
- if (!result.contains(phoneNo))
- result.add(phoneNo);
- }
- pCur.close();
- return result;
- }
- /**
- * Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
- * @param context Context reference to get the TelephonyManager instance from
- * @return country code or null
- */
- private static String getUserCountry(Context context) {
- try {
- final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
- final String simCountry = tm.getSimCountryIso();
- if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
- return simCountry.toUpperCase();
- }
- else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
- String networkCountry = tm.getNetworkCountryIso();
- if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
- return networkCountry.toUpperCase();
- }
- }
- }
- catch (Exception e) {
- System.err.println("Can't get user country: " + e.toString());
- }
- return null;
- }
- /**
- * Synchronize all raw contacts
- *
- * @param context The context of Authenticator Activity
- * @param account The username for the account
- * @param contacts The collection of profiles
- */
- public static synchronized void syncContacts(Context context, String account, Collection<Contact> contacts) {
- for (Contact contact : contacts)
- syncContact(context, account, contact);
- }
- /**
- * Synchronize raw contact
- *
- * @param context The context of Authenticator Activity
- * @param account The username for the account
- * @param contact The contact to sync
- */
- public static synchronized void syncContact(Context context, String account, Contact contact) {
- if(TextUtils.isEmpty(contact.getPhone()))
- return;
- final ContentResolver resolver = context.getContentResolver();
- final BatchOperation batchOperation = new BatchOperation(context, resolver);
- Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
- Uri.encode(contact.getPhone()));
- Cursor contactCursor = resolver.query(
- lookupUri,
- new String[]{ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.LOOKUP_KEY},
- null, null, null);
- if (contactCursor.moveToFirst()) {
- long contactId = contactCursor.getLong(0);
- long rawContactId = lookupRawContact(resolver, contactId);
- if (rawContactId != 0 && !isDeletedRawContact(context, rawContactId)) {
- backupContact(context, resolver, rawContactId);
- recreateContact(context, resolver, account, contact, rawContactId, batchOperation);
- batchOperation.execute();
- deleteContact(context, rawContactId, batchOperation);
- }
- else
- addContact(context, account, contact, batchOperation);
- } else
- addContact(context, account, contact, batchOperation);
- contactCursor.close();
- batchOperation.execute();
- }
- /**
- * Checks if contact marked as deleted
- *
- * @param context The context of Authenticator Activity
- * @param rowContactId ID of the verifiable contact
- */
- private static boolean isDeletedRawContact(Context context, long rawContactId) {
- Cursor c = context.getContentResolver().query(RawContacts.CONTENT_URI,
- new String[]{RawContacts.DELETED},
- RawContacts._ID + "=?",
- new String[]{String.valueOf(rawContactId)}, null);
- c.moveToFirst();
- boolean result = c.getInt(0) > 0;
- c.close();
- return result;
- }
- /**
- * Restores previously recreated contacts.
- *
- * @param context The context of Authenticator Activity
- */
- public static void restoreContact(Context context) {
- String path = FileHelper.getExternalFilesDir().toString() + File.separator + CONTACTS_FILE;
- File file = new File(path);
- int length = (int) file.length();
- byte[] bytes = new byte[length];
- try {
- FileInputStream in = new FileInputStream(file);
- in.read(bytes);
- }
- catch (Exception e1) {
- Log.e(TAG, "Error restoring contact. " + e1.toString());
- }
- String contactString = new String(bytes);
- final ContentResolver resolver = context.getContentResolver();
- final BatchOperation batchOperation = new BatchOperation(context, resolver);
- final ContactOperations contactOp = ContactOperations.createBackupContact(context, batchOperation);
- String separator = System.getProperty("line.separator");
- while (contactString.length() > 0) {
- int i = contactString.indexOf(separator);
- String mimeType = contactString.substring(0, i);
- int ii = contactString.indexOf(separator + separator);
- if (ii - i < 1) {
- contactString = contactString.substring(ii + separator.length() * 2);
- continue;
- }
- contactString = contactString.substring(i + separator.length());
- String data[] = new String[3];
- for (int j = 0; j < 4; j++) {
- i = contactString.indexOf(separator);
- if (i == 0) {
- contactString = contactString.substring(separator.length());
- break;
- }
- data[j] = contactString.substring(0, i);
- contactString = contactString.substring(i + separator.length());
- }
- contactOp.addData(data[0], data[1], data[2], mimeType);
- if (contactString.indexOf(separator) == 0)
- break;
- }
- batchOperation.execute();
- }
- /**
- * Adds a single contact to the platform contacts provider.
- *
- * @param context the Authenticator Activity context
- * @param accountName the account the contact belongs to
- * @param profile the sample SyncAdapter User object
- */
- private static void addContact(Context context, String accountName, Profile profile, BatchOperation batchOperation) {
- final ContactOperations contactOp =
- ContactOperations.createNewContact(context, accountName, batchOperation);
- contactOp.addEmail(profile.getEmail())
- .addPhone(profile.getPhone(), Phone.TYPE_MOBILE)
- .addName(profile.getGivenName(), profile.getFamilyName(), profile.getNickname())
- // .addProfileAction(profileId)
- .addIMData(accountName, profile.getNickname());
- }
- ...
- /**
- * Updates a single contact to the platform contacts provider.
- *
- * @param context the Authenticator Activity context
- * @param resolver the ContentResolver to use
- * @param accountName the account the contact belongs to
- * @param user the sample SyncAdapter contact object.
- * @param rawContactId the unique Id for this rawContact in contacts
- * provider
- */
- private static void updateContact(Context context,
- ContentResolver resolver,
- String accountName,
- Profile user,
- long contactId, long rawContactId,
- BatchOperation batchOperation) {
- Uri uri;
- String cellPhone = null;
- String email = null;
- String givenName = null, familyName = null, nickName = null;
- String chiemoSync = null;
- boolean newEmail = true;
- boolean newIM = true;
- final Cursor c = resolver.query(
- Data.CONTENT_URI,
- DataQuery.PROJECTION,
- DataQuery.SELECTION,
- new String[]{String.valueOf(rawContactId)},
- null);
- final ContactOperations contactOp = ContactOperations.updateExistingContact(context, rawContactId, batchOperation);
- try { // prepare information that needs updating
- while (c.moveToNext()) {
- final long id = c.getLong(DataQuery.COLUMN_ID);
- final String mimeType = c.getString(DataQuery.COLUMN_MIMETYPE);
- uri = ContentUris.withAppendedId(Data.CONTENT_URI, id);
- if (mimeType.equals(StructuredName.CONTENT_ITEM_TYPE)) {
- givenName = c.getString(DataQuery.COLUMN_GIVEN_NAME);
- familyName = c.getString(DataQuery.COLUMN_FAMILY_NAME);
- } else if (mimeType.equals(Phone.CONTENT_ITEM_TYPE)) {
- final int type = c.getInt(DataQuery.COLUMN_PHONE_TYPE);
- if (type == Phone.TYPE_MOBILE) {
- cellPhone = c.getString(DataQuery.COLUMN_PHONE_NUMBER);
- contactOp.updatePhone(cellPhone, user.getPhone(), uri);
- }
- } else if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
- email = c.getString(DataQuery.COLUMN_EMAIL_ADDRESS);
- if (email.equals(user.getEmail()))
- newEmail = false;
- } else if (mimeType.equals(ContactOperations.MIMETYPE_CHIEMO_CUSTOM)) {
- chiemoSync = c.getString(DataQuery.COLUMN_DATA3);
- if (user.getNickname().equals(chiemoSync.substring(chiemoSync.lastIndexOf(" "))))
- newIM = false;
- }
- } // while
- } finally {
- c.close();
- }
- // Add name, if present and not updated
- if (givenName == null && familyName == null) {
- contactOp.addName(user.getGivenName(), user.getFamilyName(), user.getNickname());
- } else if (givenName.length() < 1 && familyName.length() < 1) {
- contactOp.addName(user.getGivenName(), user.getFamilyName(), user.getNickname());
- }
- // Add the phone, if present and not updated above
- if (cellPhone == null)
- contactOp.addPhone(user.getPhone(), Phone.TYPE_MOBILE);
- // Add the email address, if present and not updated above
- if (email == null || newEmail)
- contactOp.addEmail(user.getEmail());
- // Add chiemo sync, if present and not updated above
- if (chiemoSync == null || newIM)
- contactOp.addIMData(accountName, user.getNickname());
- }
- /**
- * Updates a single contact to the platform contacts provider.
- *
- * @param context the Authenticator Activity context
- * @param resolver the ContentResolver to use
- * @param accountName the account the contact belongs to
- * @param user the sample SyncAdapter contact object.
- * @param rawContactId the unique Id for this rawContact in contacts
- * provider
- */
- private static void recreateContact(Context context, ContentResolver resolver, String accountName, Profile user, long rawContactId, BatchOperation batchOperation) {
- String cellPhone = null;
- String email = null;
- String givenName = null, familyName = null;
- boolean newEmail = true;
- boolean newPhone = true;
- boolean isChiemoContact = false;
- final Cursor c = resolver.query(
- Data.CONTENT_URI,
- DataQuery.PROJECTION,
- DataQuery.SELECTION,
- new String[]{String.valueOf(rawContactId)},
- null);
- final ContactOperations contactOp = ContactOperations.createNewContact(context, accountName, batchOperation);
- try {
- while (c.moveToNext()) {
- final String mimeType = c.getString(DataQuery.COLUMN_MIMETYPE);
- switch (mimeType) {
- case StructuredName.CONTENT_ITEM_TYPE:
- givenName = c.getString(DataQuery.COLUMN_GIVEN_NAME);
- familyName = c.getString(DataQuery.COLUMN_FAMILY_NAME);
- if ((!TextUtils.isEmpty(givenName) && givenName.length() > 0) || (!TextUtils.isEmpty(familyName) && familyName.length() > 0))
- contactOp.addName(givenName, familyName, user.getNickname());
- break;
- case Phone.CONTENT_ITEM_TYPE:
- final int type = c.getInt(DataQuery.COLUMN_PHONE_TYPE);
- cellPhone = c.getString(DataQuery.COLUMN_PHONE_NUMBER);
- contactOp.addPhone(cellPhone, type);
- if (cellPhone.equals(user.getPhone()))
- newPhone = false;
- break;
- case ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE:
- email = c.getString(DataQuery.COLUMN_EMAIL_ADDRESS);
- contactOp.addEmail(email);
- if (email.equals(user.getEmail()))
- newEmail = false;
- break;
- case ContactOperations.MIMETYPE_CHIEMO_CUSTOM: {
- String data1 = c.getString(DataQuery.COLUMN_DATA1);
- String data2 = c.getString(DataQuery.COLUMN_DATA2);
- String data3 = c.getString(DataQuery.COLUMN_DATA3);
- contactOp.addData(data1, data2, data3, mimeType);
- isChiemoContact = true;
- break;
- }
- default: {
- String data1 = c.getString(DataQuery.COLUMN_DATA1);
- String data2 = c.getString(DataQuery.COLUMN_DATA2);
- String data3 = c.getString(DataQuery.COLUMN_DATA3);
- contactOp.addData(data1, data2, data3, mimeType);
- break;
- }
- }
- } // while
- } finally {
- c.close();
- }
- // Add name, if present and not updated
- if (givenName == null && familyName == null) {
- contactOp.addName(user.getGivenName(), user.getFamilyName(), user.getNickname());
- }
- // Add the phone, if present and not updated above
- if (cellPhone == null || newPhone)
- contactOp.addPhone(user.getPhone(), Phone.TYPE_MOBILE);
- // Add the email address, if present and not updated above
- if (email == null || newEmail)
- contactOp.addEmail(user.getEmail());
- // Add chiemo sync, if present and not updated above
- // if (chiemoSync == null || newIM)
- if (!isChiemoContact)
- contactOp.addIMData(accountName, user.getNickname());
- // if (!isChiemoContact)
- // createBackupContact(context, accountName, rawContactId, batchOperation);
- }
- /**
- * Deletes a contact from the platform contacts provider.
- *
- * @param context the Authenticator Activity context
- * @param rawContactId the unique Id for this rawContact in contacts
- * provider
- */
- private static void deleteContact(Context context, long rawContactId, BatchOperation batchOperation) {
- batchOperation.add(ContactOperations.newDeleteCpo(
- ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), true)
- .build());
- }
- /**
- * Returns the RawContact id for a sample SyncAdapter contact, or 0 if the
- * sample SyncAdapter user isn't found.
- *
- * @param profileId the sample SyncAdapter user ID to lookup
- * @return the RawContact id, or 0 if not found
- */
- private static long lookupRawContact(ContentResolver resolver, long profileId) {
- long authorId = 0;
- final Cursor c = resolver.query(
- RawContacts.CONTENT_URI,
- UserIdQuery.PROJECTION,
- UserIdQuery.SELECTION,
- new String[]{String.valueOf(profileId)},
- null);
- try {
- if (c.moveToFirst()) {
- authorId = c.getLong(UserIdQuery.COLUMN_ID);
- }
- } finally {
- if (c != null) {
- c.close();
- }
- }
- return authorId;
- }
- /**
- * Returns the Data id for a sample SyncAdapter contact's profile row, or 0
- * if the sample SyncAdapter user isn't found.
- *
- * @param resolver a content resolver
- * @param userId the sample SyncAdapter user ID to lookup
- * @return the profile Data row id, or 0 if not found
- */
- private static long lookupProfile(ContentResolver resolver, long userId) {
- long profileId = 0;
- final Cursor c = resolver.query(
- Data.CONTENT_URI,
- ProfileQuery.PROJECTION,
- ProfileQuery.SELECTION,
- new String[]{String.valueOf(userId)},
- null);
- try {
- if (c != null && c.moveToFirst()) {
- profileId = c.getLong(ProfileQuery.COLUMN_ID);
- }
- } finally {
- if (c != null) {
- c.close();
- }
- }
- return profileId;
- }
- /**
- * Constants for a query to find a contact given a sample SyncAdapter user
- * ID.
- */
- private interface ProfileQuery {
- public final static String[] PROJECTION = new String[]{Data._ID};
- public final static int COLUMN_ID = 0;
- public static final String SELECTION =
- Data.MIMETYPE + "='" + ContactOperations.MIME_PROFILE + "' AND " + ContactOperations.DATA_PID + "=?";
- }
- /**
- * Constants for a query to find a contact given a sample SyncAdapter user
- * ID.
- */
- private interface UserIdQuery {
- public final static String[] PROJECTION = new String[]{RawContacts._ID};
- public final static int COLUMN_ID = 0;
- public static final String SELECTION = RawContacts.CONTACT_ID + "=?";
- }
- /**
- * Constants for a query to get contact data for a given rawContactId
- */
- private interface DataQuery {
- public static final String[] PROJECTION =
- new String[]{Data._ID, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3};
- public static final int COLUMN_ID = 0;
- public static final int COLUMN_MIMETYPE = 1;
- public static final int COLUMN_DATA1 = 2;
- public static final int COLUMN_DATA2 = 3;
- public static final int COLUMN_DATA3 = 4;
- public static final int COLUMN_PHONE_NUMBER = COLUMN_DATA1;
- public static final int COLUMN_PHONE_TYPE = COLUMN_DATA2;
- public static final int COLUMN_EMAIL_ADDRESS = COLUMN_DATA1;
- public static final int COLUMN_EMAIL_TYPE = COLUMN_DATA2;
- public static final int COLUMN_GIVEN_NAME = COLUMN_DATA2;
- public static final int COLUMN_FAMILY_NAME = COLUMN_DATA3;
- public static final String SELECTION = Data.RAW_CONTACT_ID + "=?";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement