From 7c0661983d95003d4ce2294050803cd4a37d16ac Mon Sep 17 00:00:00 2001 From: tibbi Date: Wed, 28 Nov 2018 21:52:38 +0100 Subject: [PATCH] moving some Activity extension responsibilities to Context --- app/build.gradle | 2 +- .../contacts/pro/extensions/Activity.kt | 101 --------- .../contacts/pro/extensions/Context.kt | 104 ++++++++- .../contacts/pro/helpers/ContactsHelper.kt | 199 +++++++++--------- .../pro/helpers/LocalContactsHelper.kt | 28 +-- 5 files changed, 215 insertions(+), 219 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index d70f8bcb..481b78b3 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -51,7 +51,7 @@ android { } dependencies { - implementation 'com.simplemobiletools:commons:5.4.7' + implementation 'com.simplemobiletools:commons:5.5.0' implementation 'joda-time:joda-time:2.10.1' implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha2' implementation 'com.googlecode.ez-vcard:ez-vcard:0.10.4' diff --git a/app/src/main/kotlin/com/simplemobiletools/contacts/pro/extensions/Activity.kt b/app/src/main/kotlin/com/simplemobiletools/contacts/pro/extensions/Activity.kt index 0b4d439d..cda4b77a 100644 --- a/app/src/main/kotlin/com/simplemobiletools/contacts/pro/extensions/Activity.kt +++ b/app/src/main/kotlin/com/simplemobiletools/contacts/pro/extensions/Activity.kt @@ -1,9 +1,7 @@ package com.simplemobiletools.contacts.pro.extensions -import android.app.Activity import android.content.Intent import android.net.Uri -import android.provider.ContactsContract import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.dialogs.RadioGroupDialog import com.simplemobiletools.commons.extensions.sharePathIntent @@ -17,8 +15,6 @@ import com.simplemobiletools.contacts.pro.activities.SimpleActivity import com.simplemobiletools.contacts.pro.dialogs.CallConfirmationDialog import com.simplemobiletools.contacts.pro.helpers.* import com.simplemobiletools.contacts.pro.models.Contact -import com.simplemobiletools.contacts.pro.models.ContactSource -import java.io.File fun SimpleActivity.startCallIntent(recipient: String) { handlePermission(PERMISSION_CALL_PHONE) { @@ -93,13 +89,6 @@ fun SimpleActivity.showContactSourcePicker(currentSource: String, callback: (new } } -fun SimpleActivity.getPublicContactSource(source: String): String { - return when (source) { - config.localAccountName -> getString(R.string.phone_storage) - SMT_PRIVATE -> getString(R.string.phone_storage_hidden) - else -> source - } -} fun BaseSimpleActivity.shareContacts(contacts: ArrayList) { val file = getTempFile() @@ -117,96 +106,6 @@ fun BaseSimpleActivity.shareContacts(contacts: ArrayList) { } } -fun BaseSimpleActivity.sendSMSToContacts(contacts: ArrayList) { - val numbers = StringBuilder() - contacts.forEach { - val number = it.phoneNumbers.firstOrNull { it.type == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE } - ?: it.phoneNumbers.firstOrNull() - if (number != null) { - numbers.append("${number.value};") - } - - val uriString = "smsto:${numbers.toString().trimEnd(';')}" - Intent(Intent.ACTION_SENDTO, Uri.parse(uriString)).apply { - if (resolveActivity(packageManager) != null) { - startActivity(this) - } else { - toast(R.string.no_app_found) - } - } - } -} - -fun BaseSimpleActivity.sendEmailToContacts(contacts: ArrayList) { - val emails = ArrayList() - contacts.forEach { - it.emails.forEach { - if (it.value.isNotEmpty()) { - emails.add(it.value) - } - } - } - - Intent(Intent.ACTION_SEND_MULTIPLE).apply { - type = "message/rfc822" - putExtra(Intent.EXTRA_EMAIL, emails.toTypedArray()) - if (resolveActivity(packageManager) != null) { - startActivity(this) - } else { - toast(R.string.no_app_found) - } - } -} - -fun BaseSimpleActivity.getTempFile(): File? { - val folder = File(cacheDir, "contacts") - if (!folder.exists()) { - if (!folder.mkdir()) { - toast(R.string.unknown_error_occurred) - return null - } - } - - return File(folder, "contacts.vcf") -} - -fun BaseSimpleActivity.addContactsToGroup(contacts: ArrayList, groupId: Long) { - val publicContacts = contacts.filter { it.source != SMT_PRIVATE }.toMutableList() as ArrayList - val privateContacts = contacts.filter { it.source == SMT_PRIVATE }.toMutableList() as ArrayList - if (publicContacts.isNotEmpty()) { - ContactsHelper(this).addContactsToGroup(publicContacts, groupId) - } - - if (privateContacts.isNotEmpty()) { - LocalContactsHelper(this).addContactsToGroup(privateContacts, groupId) - } -} - -fun BaseSimpleActivity.removeContactsFromGroup(contacts: ArrayList, groupId: Long) { - val publicContacts = contacts.filter { it.source != SMT_PRIVATE }.toMutableList() as ArrayList - val privateContacts = contacts.filter { it.source == SMT_PRIVATE }.toMutableList() as ArrayList - if (publicContacts.isNotEmpty() && hasContactPermissions()) { - ContactsHelper(this).removeContactsFromGroup(publicContacts, groupId) - } - - if (privateContacts.isNotEmpty()) { - LocalContactsHelper(this).removeContactsFromGroup(privateContacts, groupId) - } -} - -fun BaseSimpleActivity.getContactPublicUri(contact: Contact): Uri { - val lookupKey = ContactsHelper(this).getContactLookupKey(contact.id.toString()) - return Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey) -} - -fun Activity.getVisibleContactSources(): ArrayList { - val sources = ContactsHelper(this).getDeviceContactSources() - sources.add(ContactSource(getString(R.string.phone_storage_hidden), SMT_PRIVATE)) - val sourceNames = ArrayList(sources).map { if (it.type == SMT_PRIVATE) SMT_PRIVATE else it.name }.toMutableList() as ArrayList - sourceNames.removeAll(config.ignoredContactSources) - return sourceNames -} - fun SimpleActivity.contactClicked(contact: Contact) { when (config.onContactClick) { ON_CLICK_CALL_CONTACT -> callContact(contact) diff --git a/app/src/main/kotlin/com/simplemobiletools/contacts/pro/extensions/Context.kt b/app/src/main/kotlin/com/simplemobiletools/contacts/pro/extensions/Context.kt index cf675e63..0f221c25 100644 --- a/app/src/main/kotlin/com/simplemobiletools/contacts/pro/extensions/Context.kt +++ b/app/src/main/kotlin/com/simplemobiletools/contacts/pro/extensions/Context.kt @@ -16,13 +16,11 @@ import com.simplemobiletools.contacts.pro.R import com.simplemobiletools.contacts.pro.activities.EditContactActivity import com.simplemobiletools.contacts.pro.activities.ViewContactActivity import com.simplemobiletools.contacts.pro.databases.ContactsDatabase -import com.simplemobiletools.contacts.pro.helpers.CONTACT_ID -import com.simplemobiletools.contacts.pro.helpers.Config -import com.simplemobiletools.contacts.pro.helpers.IS_PRIVATE -import com.simplemobiletools.contacts.pro.helpers.SMT_PRIVATE +import com.simplemobiletools.contacts.pro.helpers.* import com.simplemobiletools.contacts.pro.interfaces.ContactsDao import com.simplemobiletools.contacts.pro.interfaces.GroupsDao import com.simplemobiletools.contacts.pro.models.Contact +import com.simplemobiletools.contacts.pro.models.ContactSource import com.simplemobiletools.contacts.pro.models.Organization import java.io.File @@ -184,3 +182,101 @@ fun Context.getPhotoThumbnailSize(): Int { } fun Context.hasContactPermissions() = hasPermission(PERMISSION_READ_CONTACTS) && hasPermission(PERMISSION_WRITE_CONTACTS) + +fun Context.getPublicContactSource(source: String): String { + return when (source) { + config.localAccountName -> getString(R.string.phone_storage) + SMT_PRIVATE -> getString(R.string.phone_storage_hidden) + else -> source + } +} + +fun Context.sendSMSToContacts(contacts: ArrayList) { + val numbers = StringBuilder() + contacts.forEach { + val number = it.phoneNumbers.firstOrNull { it.type == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE } + ?: it.phoneNumbers.firstOrNull() + if (number != null) { + numbers.append("${number.value};") + } + + val uriString = "smsto:${numbers.toString().trimEnd(';')}" + Intent(Intent.ACTION_SENDTO, Uri.parse(uriString)).apply { + if (resolveActivity(packageManager) != null) { + startActivity(this) + } else { + toast(R.string.no_app_found) + } + } + } +} + +fun Context.sendEmailToContacts(contacts: ArrayList) { + val emails = ArrayList() + contacts.forEach { + it.emails.forEach { + if (it.value.isNotEmpty()) { + emails.add(it.value) + } + } + } + + Intent(Intent.ACTION_SEND_MULTIPLE).apply { + type = "message/rfc822" + putExtra(Intent.EXTRA_EMAIL, emails.toTypedArray()) + if (resolveActivity(packageManager) != null) { + startActivity(this) + } else { + toast(R.string.no_app_found) + } + } +} + +fun Context.getTempFile(): File? { + val folder = File(cacheDir, "contacts") + if (!folder.exists()) { + if (!folder.mkdir()) { + toast(R.string.unknown_error_occurred) + return null + } + } + + return File(folder, "contacts.vcf") +} + +fun Context.addContactsToGroup(contacts: ArrayList, groupId: Long) { + val publicContacts = contacts.filter { it.source != SMT_PRIVATE }.toMutableList() as ArrayList + val privateContacts = contacts.filter { it.source == SMT_PRIVATE }.toMutableList() as ArrayList + if (publicContacts.isNotEmpty()) { + ContactsHelper(this).addContactsToGroup(publicContacts, groupId) + } + + if (privateContacts.isNotEmpty()) { + LocalContactsHelper(this).addContactsToGroup(privateContacts, groupId) + } +} + +fun Context.removeContactsFromGroup(contacts: ArrayList, groupId: Long) { + val publicContacts = contacts.filter { it.source != SMT_PRIVATE }.toMutableList() as ArrayList + val privateContacts = contacts.filter { it.source == SMT_PRIVATE }.toMutableList() as ArrayList + if (publicContacts.isNotEmpty() && hasContactPermissions()) { + ContactsHelper(this).removeContactsFromGroup(publicContacts, groupId) + } + + if (privateContacts.isNotEmpty()) { + LocalContactsHelper(this).removeContactsFromGroup(privateContacts, groupId) + } +} + +fun Context.getContactPublicUri(contact: Contact): Uri { + val lookupKey = ContactsHelper(this).getContactLookupKey(contact.id.toString()) + return Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey) +} + +fun Context.getVisibleContactSources(): ArrayList { + val sources = ContactsHelper(this).getDeviceContactSources() + sources.add(ContactSource(getString(R.string.phone_storage_hidden), SMT_PRIVATE)) + val sourceNames = ArrayList(sources).map { if (it.type == SMT_PRIVATE) SMT_PRIVATE else it.name }.toMutableList() as ArrayList + sourceNames.removeAll(config.ignoredContactSources) + return sourceNames +} diff --git a/app/src/main/kotlin/com/simplemobiletools/contacts/pro/helpers/ContactsHelper.kt b/app/src/main/kotlin/com/simplemobiletools/contacts/pro/helpers/ContactsHelper.kt index 1ab00f31..ac2312a9 100644 --- a/app/src/main/kotlin/com/simplemobiletools/contacts/pro/helpers/ContactsHelper.kt +++ b/app/src/main/kotlin/com/simplemobiletools/contacts/pro/helpers/ContactsHelper.kt @@ -3,11 +3,12 @@ package com.simplemobiletools.contacts.pro.helpers import android.accounts.Account import android.accounts.AccountManager import android.annotation.SuppressLint -import android.app.Activity import android.content.* import android.database.Cursor import android.graphics.Bitmap import android.net.Uri +import android.os.Handler +import android.os.Looper import android.provider.CallLog import android.provider.ContactsContract import android.provider.ContactsContract.CommonDataKinds @@ -26,24 +27,24 @@ import java.text.SimpleDateFormat import java.util.* import kotlin.collections.ArrayList -class ContactsHelper(val activity: Activity) { +class ContactsHelper(val context: Context) { private val BATCH_SIZE = 100 private var displayContactSources = ArrayList() fun getContacts(callback: (ArrayList) -> Unit) { Thread { val contacts = SparseArray() - displayContactSources = activity.getVisibleContactSources() + displayContactSources = context.getVisibleContactSources() getDeviceContacts(contacts) if (displayContactSources.contains(SMT_PRIVATE)) { - LocalContactsHelper(activity).getAllContacts().forEach { + LocalContactsHelper(context).getAllContacts().forEach { contacts.put(it.id, it) } } val contactsSize = contacts.size() - val showOnlyContactsWithNumbers = activity.config.showOnlyContactsWithNumbers + val showOnlyContactsWithNumbers = context.config.showOnlyContactsWithNumbers var tempContacts = ArrayList(contactsSize) val resultContacts = ArrayList(contactsSize) @@ -57,7 +58,7 @@ class ContactsHelper(val activity: Activity) { contacts.valueAt(it) } - if (activity.config.filterDuplicates) { + if (context.config.filterDuplicates) { tempContacts = tempContacts.distinctBy { it.getHashToCompare() } as ArrayList @@ -82,11 +83,11 @@ class ContactsHelper(val activity: Activity) { resultContacts.firstOrNull { it.contactId == key }?.groups = groups.valueAt(i) } - Contact.sorting = activity.config.sorting - Contact.startWithSurname = activity.config.startNameWithSurname + Contact.sorting = context.config.sorting + Contact.startWithSurname = context.config.startNameWithSurname resultContacts.sort() - activity.runOnUiThread { + Handler(Looper.getMainLooper()).post { callback(resultContacts) } }.start() @@ -101,19 +102,19 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) callback(getContactWithId(id, false)) return@Thread } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } - callback(LocalContactsHelper(activity).getContactWithNumber(number)) + callback(LocalContactsHelper(context).getContactWithNumber(number)) }.start() } @@ -127,7 +128,7 @@ class ContactsHelper(val activity: Activity) { val sources = HashSet() var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, null, null, null) + cursor = context.contentResolver.query(uri, projection, null, null, null) if (cursor?.moveToFirst() == true) { do { val name = cursor.getStringValue(ContactsContract.RawContacts.ACCOUNT_NAME) ?: "" @@ -145,7 +146,7 @@ class ContactsHelper(val activity: Activity) { } private fun getDeviceContacts(contacts: SparseArray) { - if (!activity.hasContactPermissions()) { + if (!context.hasContactPermissions()) { return } @@ -157,7 +158,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, sortOrder) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, sortOrder) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) @@ -188,7 +189,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -276,7 +277,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) @@ -294,7 +295,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -315,7 +316,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) @@ -324,7 +325,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -347,7 +348,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) @@ -363,7 +364,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -386,7 +387,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) @@ -402,7 +403,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -425,7 +426,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) @@ -441,7 +442,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -463,7 +464,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) @@ -478,7 +479,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -499,7 +500,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) @@ -508,7 +509,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -530,7 +531,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) @@ -545,7 +546,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -566,7 +567,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) @@ -580,7 +581,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -590,7 +591,7 @@ class ContactsHelper(val activity: Activity) { private fun getContactGroups(storedGroups: ArrayList, contactId: Int? = null): SparseArray> { val groups = SparseArray>() - if (!activity.hasContactPermissions()) { + if (!context.hasContactPermissions()) { return groups } @@ -605,7 +606,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(ContactsContract.Data.CONTACT_ID) @@ -620,7 +621,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -673,7 +674,7 @@ class ContactsHelper(val activity: Activity) { fun getStoredGroups(callback: (ArrayList) -> Unit) { Thread { val groups = getStoredGroupsSync() - activity.runOnUiThread { + Handler(Looper.getMainLooper()).post { callback(groups) } }.start() @@ -681,13 +682,13 @@ class ContactsHelper(val activity: Activity) { fun getStoredGroupsSync(): ArrayList { val groups = getDeviceStoredGroups() - groups.addAll(activity.groupsDB.getGroups()) + groups.addAll(context.groupsDB.getGroups()) return groups } fun getDeviceStoredGroups(): ArrayList { val groups = ArrayList() - if (!activity.hasContactPermissions()) { + if (!context.hasContactPermissions()) { return groups } @@ -703,7 +704,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { do { val id = cursor.getLongValue(ContactsContract.Groups._ID) @@ -718,7 +719,7 @@ class ContactsHelper(val activity: Activity) { } while (cursor.moveToNext()) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } finally { cursor?.close() } @@ -728,7 +729,7 @@ class ContactsHelper(val activity: Activity) { fun createNewGroup(title: String, accountName: String, accountType: String): Group? { if (accountType == SMT_PRIVATE) { val newGroup = Group(null, title) - val id = activity.groupsDB.insertOrUpdate(newGroup) + val id = context.groupsDB.insertOrUpdate(newGroup) newGroup.id = id return newGroup } @@ -743,11 +744,11 @@ class ContactsHelper(val activity: Activity) { } try { - val results = activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + val results = context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) val rawId = ContentUris.parseId(results[0].uri) return Group(rawId, title) } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } return null } @@ -763,9 +764,9 @@ class ContactsHelper(val activity: Activity) { } try { - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } } @@ -778,9 +779,9 @@ class ContactsHelper(val activity: Activity) { operations.add(ContentProviderOperation.newDelete(uri).build()) try { - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } } @@ -788,7 +789,7 @@ class ContactsHelper(val activity: Activity) { if (id == 0) { return null } else if (isLocalPrivate) { - return LocalContactsHelper(activity).getContactWithId(id) + return LocalContactsHelper(context).getContactWithId(id) } val selection = "${ContactsContract.Data.MIMETYPE} = ? AND ${ContactsContract.Data.RAW_CONTACT_ID} = ?" @@ -808,7 +809,7 @@ class ContactsHelper(val activity: Activity) { val projection = getContactProjection() var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { val id = cursor.getIntValue(ContactsContract.Data.RAW_CONTACT_ID) val prefix = cursor.getStringValue(CommonDataKinds.StructuredName.PREFIX) ?: "" @@ -849,22 +850,22 @@ class ContactsHelper(val activity: Activity) { private fun getContactSourcesSync(): ArrayList { val sources = getDeviceContactSources() - sources.add(ContactSource(activity.getString(R.string.phone_storage_hidden), SMT_PRIVATE)) + sources.add(ContactSource(context.getString(R.string.phone_storage_hidden), SMT_PRIVATE)) return ArrayList(sources) } fun getDeviceContactSources(): LinkedHashSet { val sources = LinkedHashSet() - if (!activity.hasContactPermissions()) { + if (!context.hasContactPermissions()) { return sources } - val accounts = AccountManager.get(activity).accounts + val accounts = AccountManager.get(context).accounts accounts.forEach { if (ContentResolver.getIsSyncable(it, ContactsContract.AUTHORITY) == 1) { val contactSource = ContactSource(it.name, it.type) if (it.type == TELEGRAM_PACKAGE) { - contactSource.name += " (${activity.getString(R.string.telegram)})" + contactSource.name += " (${context.getString(R.string.telegram)})" } sources.add(contactSource) } @@ -875,7 +876,7 @@ class ContactsHelper(val activity: Activity) { } sources.addAll(contentResolverAccounts) - if (sources.isEmpty() && activity.config.localAccountName.isEmpty() && activity.config.localAccountType.isEmpty()) { + if (sources.isEmpty() && context.config.localAccountName.isEmpty() && context.config.localAccountType.isEmpty()) { sources.add(ContactSource("", "")) } @@ -899,7 +900,7 @@ class ContactsHelper(val activity: Activity) { ) private fun getSortString(): String { - val sorting = activity.config.sorting + val sorting = context.config.sorting var sort = when { sorting and SORT_BY_FIRST_NAME != 0 -> "${CommonDataKinds.StructuredName.GIVEN_NAME} COLLATE NOCASE" sorting and SORT_BY_MIDDLE_NAME != 0 -> "${CommonDataKinds.StructuredName.MIDDLE_NAME} COLLATE NOCASE" @@ -921,7 +922,7 @@ class ContactsHelper(val activity: Activity) { val selectionArgs = arrayOf(CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, id.toString()) var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { return cursor.getIntValue(ContactsContract.Data.CONTACT_ID) } @@ -933,9 +934,9 @@ class ContactsHelper(val activity: Activity) { } fun updateContact(contact: Contact, photoUpdateStatus: Int): Boolean { - activity.toast(R.string.updating) + context.toast(R.string.updating) if (contact.source == SMT_PRIVATE) { - return LocalContactsHelper(activity).insertOrUpdateContact(contact) + return LocalContactsHelper(context).insertOrUpdateContact(contact) } try { @@ -1149,9 +1150,9 @@ class ContactsHelper(val activity: Activity) { val uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, contact.contactId.toString()) val contentValues = ContentValues(1) contentValues.put(ContactsContract.Contacts.STARRED, contact.starred) - activity.contentResolver.update(uri, contentValues, null, null) + context.contentResolver.update(uri, contentValues, null, null) } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } // photo @@ -1160,10 +1161,10 @@ class ContactsHelper(val activity: Activity) { PHOTO_REMOVED -> removePhoto(contact, operations) } - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) return true } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) return false } } @@ -1171,9 +1172,9 @@ class ContactsHelper(val activity: Activity) { private fun addPhoto(contact: Contact, operations: ArrayList): ArrayList { if (contact.photoUri.isNotEmpty()) { val photoUri = Uri.parse(contact.photoUri) - val bitmap = MediaStore.Images.Media.getBitmap(activity.contentResolver, photoUri) + val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, photoUri) - val thumbnailSize = activity.getPhotoThumbnailSize() + val thumbnailSize = context.getPhotoThumbnailSize() val scaledPhoto = Bitmap.createScaledBitmap(bitmap, thumbnailSize, thumbnailSize, false) val scaledSizePhotoData = scaledPhoto.getByteArray() scaledPhoto.recycle() @@ -1215,15 +1216,15 @@ class ContactsHelper(val activity: Activity) { } if (operations.size % BATCH_SIZE == 0) { - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) operations.clear() } } try { - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } } @@ -1238,16 +1239,16 @@ class ContactsHelper(val activity: Activity) { } if (operations.size % BATCH_SIZE == 0) { - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) operations.clear() } } - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) } fun insertContact(contact: Contact): Boolean { if (contact.source == SMT_PRIVATE) { - return LocalContactsHelper(activity).insertOrUpdateContact(contact) + return LocalContactsHelper(context).insertOrUpdateContact(contact) } try { @@ -1386,9 +1387,9 @@ class ContactsHelper(val activity: Activity) { var scaledSizePhotoData: ByteArray? if (contact.photoUri.isNotEmpty()) { val photoUri = Uri.parse(contact.photoUri) - val bitmap = MediaStore.Images.Media.getBitmap(activity.contentResolver, photoUri) + val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, photoUri) - val thumbnailSize = activity.getPhotoThumbnailSize() + val thumbnailSize = context.getPhotoThumbnailSize() val scaledPhoto = Bitmap.createScaledBitmap(bitmap, thumbnailSize, thumbnailSize, false) scaledSizePhotoData = scaledPhoto.getByteArray() @@ -1406,7 +1407,7 @@ class ContactsHelper(val activity: Activity) { val results: Array try { - results = activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + results = context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) } finally { scaledSizePhotoData = null } @@ -1423,12 +1424,12 @@ class ContactsHelper(val activity: Activity) { val uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, userId.toString()) val contentValues = ContentValues(1) contentValues.put(ContactsContract.Contacts.STARRED, contact.starred) - activity.contentResolver.update(uri, contentValues, null, null) + context.contentResolver.update(uri, contentValues, null, null) } return true } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) return false } } @@ -1436,7 +1437,7 @@ class ContactsHelper(val activity: Activity) { private fun addFullSizePhoto(contactId: Long, fullSizePhotoData: ByteArray) { val baseUri = ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, contactId) val displayPhotoUri = Uri.withAppendedPath(baseUri, ContactsContract.RawContacts.DisplayPhoto.CONTENT_DIRECTORY) - val fileDescriptor = activity.contentResolver.openAssetFileDescriptor(displayPhotoUri, "rw") + val fileDescriptor = context.contentResolver.openAssetFileDescriptor(displayPhotoUri, "rw") val photoStream = fileDescriptor.createOutputStream() photoStream.write(fullSizePhotoData) photoStream.close() @@ -1450,7 +1451,7 @@ class ContactsHelper(val activity: Activity) { val selectionArgs = arrayOf(CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, contactId) var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { val id = cursor.getIntValue(ContactsContract.Data.CONTACT_ID) val lookupKey = cursor.getStringValue(ContactsContract.Data.LOOKUP_KEY) @@ -1470,7 +1471,7 @@ class ContactsHelper(val activity: Activity) { var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, selection, selectionArgs, null) + cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null) if (cursor?.moveToFirst() == true) { return cursor.getStringValue(ContactsContract.Data._ID) } @@ -1483,7 +1484,7 @@ class ContactsHelper(val activity: Activity) { fun addFavorites(contacts: ArrayList) { Thread { toggleLocalFavorites(contacts, true) - if (activity.hasContactPermissions()) { + if (context.hasContactPermissions()) { toggleFavorites(contacts, true) } }.start() @@ -1492,7 +1493,7 @@ class ContactsHelper(val activity: Activity) { fun removeFavorites(contacts: ArrayList) { Thread { toggleLocalFavorites(contacts, false) - if (activity.hasContactPermissions()) { + if (context.hasContactPermissions()) { toggleFavorites(contacts, false) } }.start() @@ -1509,25 +1510,25 @@ class ContactsHelper(val activity: Activity) { } if (operations.size % BATCH_SIZE == 0) { - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) operations.clear() } } - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } } private fun toggleLocalFavorites(contacts: ArrayList, addToFavorites: Boolean) { val localContacts = contacts.filter { it.source == SMT_PRIVATE }.map { it.id }.toTypedArray() - LocalContactsHelper(activity).toggleFavorites(localContacts, addToFavorites) + LocalContactsHelper(context).toggleFavorites(localContacts, addToFavorites) } fun deleteContact(contact: Contact) { Thread { if (contact.source == SMT_PRIVATE) { - activity.contactsDB.deleteContactId(contact.id) + context.contactsDB.deleteContactId(contact.id) } else { deleteContacts(arrayListOf(contact)) } @@ -1536,7 +1537,7 @@ class ContactsHelper(val activity: Activity) { fun deleteContacts(contacts: ArrayList) { val localContacts = contacts.filter { it.source == SMT_PRIVATE }.map { it.id }.toTypedArray() - LocalContactsHelper(activity).deleteContactIds(localContacts) + LocalContactsHelper(context).deleteContactIds(localContacts) try { val operations = ArrayList() @@ -1549,16 +1550,16 @@ class ContactsHelper(val activity: Activity) { } if (operations.size % BATCH_SIZE == 0) { - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) operations.clear() } } - if (activity.hasPermission(PERMISSION_WRITE_CONTACTS)) { - activity.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) + if (context.hasPermission(PERMISSION_WRITE_CONTACTS)) { + context.contentResolver.applyBatch(ContactsContract.AUTHORITY, operations) } } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } } @@ -1566,7 +1567,7 @@ class ContactsHelper(val activity: Activity) { fun getRecents(callback: (ArrayList) -> Unit) { Thread { val calls = ArrayList() - if (!activity.hasPermission(PERMISSION_WRITE_CALL_LOG) || !activity.hasPermission(PERMISSION_READ_CALL_LOG)) { + if (!context.hasPermission(PERMISSION_WRITE_CALL_LOG) || !context.hasPermission(PERMISSION_READ_CALL_LOG)) { callback(calls) return@Thread } @@ -1584,13 +1585,13 @@ class ContactsHelper(val activity: Activity) { val currentYear = SimpleDateFormat("yyyy", Locale.getDefault()).format(currentDate) val todayDate = SimpleDateFormat("dd MMM yyyy", Locale.getDefault()).format(currentDate) val yesterdayDate = SimpleDateFormat("dd MMM yyyy", Locale.getDefault()).format(Date(System.currentTimeMillis() - DAY_SECONDS * 1000)) - val yesterday = activity.getString(R.string.yesterday) - val timeFormat = if (activity.config.use24HourFormat) "HH:mm" else "h:mm a" + val yesterday = context.getString(R.string.yesterday) + val timeFormat = if (context.config.use24HourFormat) "HH:mm" else "h:mm a" var prevNumber = "" var cursor: Cursor? = null try { - cursor = activity.contentResolver.query(uri, projection, null, null, sorting) + cursor = context.contentResolver.query(uri, projection, null, null, sorting) if (cursor?.moveToFirst() == true) { do { val id = cursor.getIntValue(CallLog.Calls._ID) @@ -1634,14 +1635,14 @@ class ContactsHelper(val activity: Activity) { } if (operations.size % BATCH_SIZE == 0) { - activity.contentResolver.applyBatch(CallLog.AUTHORITY, operations) + context.contentResolver.applyBatch(CallLog.AUTHORITY, operations) operations.clear() } } - activity.contentResolver.applyBatch(CallLog.AUTHORITY, operations) + context.contentResolver.applyBatch(CallLog.AUTHORITY, operations) } catch (e: Exception) { - activity.showErrorToast(e) + context.showErrorToast(e) } }.start() } diff --git a/app/src/main/kotlin/com/simplemobiletools/contacts/pro/helpers/LocalContactsHelper.kt b/app/src/main/kotlin/com/simplemobiletools/contacts/pro/helpers/LocalContactsHelper.kt index 438f8eee..f1f4caa5 100644 --- a/app/src/main/kotlin/com/simplemobiletools/contacts/pro/helpers/LocalContactsHelper.kt +++ b/app/src/main/kotlin/com/simplemobiletools/contacts/pro/helpers/LocalContactsHelper.kt @@ -1,6 +1,6 @@ package com.simplemobiletools.contacts.pro.helpers -import android.app.Activity +import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri @@ -14,13 +14,13 @@ import com.simplemobiletools.contacts.pro.models.Group import com.simplemobiletools.contacts.pro.models.LocalContact import com.simplemobiletools.contacts.pro.models.Organization -class LocalContactsHelper(val activity: Activity) { - fun getAllContacts() = activity.contactsDB.getContacts().map { convertLocalContactToContact(it) }.toMutableList() as ArrayList +class LocalContactsHelper(val context: Context) { + fun getAllContacts() = context.contactsDB.getContacts().map { convertLocalContactToContact(it) }.toMutableList() as ArrayList - fun getContactWithId(id: Int) = convertLocalContactToContact(activity.contactsDB.getContactWithId(id)) + fun getContactWithId(id: Int) = convertLocalContactToContact(context.contactsDB.getContactWithId(id)) fun getContactWithNumber(number: String): Contact? { - activity.contactsDB.getContacts().forEach { + context.contactsDB.getContacts().forEach { if (it.phoneNumbers.map { it.value }.contains(number)) { return convertLocalContactToContact(it) } @@ -30,7 +30,7 @@ class LocalContactsHelper(val activity: Activity) { fun insertOrUpdateContact(contact: Contact): Boolean { val localContact = convertContactToLocalContact(contact) - return activity.contactsDB.insertOrUpdate(localContact) > 0 + return context.contactsDB.insertOrUpdate(localContact) > 0 } fun addContactsToGroup(contacts: ArrayList, groupId: Long) { @@ -40,7 +40,7 @@ class LocalContactsHelper(val activity: Activity) { newGroups.add(groupId) newGroups.distinct() localContact.groups = newGroups - activity.contactsDB.insertOrUpdate(localContact) + context.contactsDB.insertOrUpdate(localContact) } } @@ -50,20 +50,20 @@ class LocalContactsHelper(val activity: Activity) { val newGroups = localContact.groups newGroups.remove(groupId) localContact.groups = newGroups - activity.contactsDB.insertOrUpdate(localContact) + context.contactsDB.insertOrUpdate(localContact) } } fun deleteContactIds(ids: Array) { ids.forEach { - activity.contactsDB.deleteContactId(it) + context.contactsDB.deleteContactId(it) } } fun toggleFavorites(ids: Array, addToFavorites: Boolean) { val isStarred = if (addToFavorites) 1 else 0 ids.forEach { - activity.contactsDB.updateStarred(isStarred, it) + context.contactsDB.updateStarred(isStarred, it) } } @@ -73,9 +73,9 @@ class LocalContactsHelper(val activity: Activity) { } val photoUri = Uri.parse(uri) - val bitmap = MediaStore.Images.Media.getBitmap(activity.contentResolver, photoUri) + val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, photoUri) - val thumbnailSize = activity.getPhotoThumbnailSize() + val thumbnailSize = context.getPhotoThumbnailSize() val scaledPhoto = Bitmap.createScaledBitmap(bitmap, thumbnailSize * 2, thumbnailSize * 2, false) val scaledSizePhotoData = scaledPhoto.getByteArray() scaledPhoto.recycle() @@ -97,9 +97,9 @@ class LocalContactsHelper(val activity: Activity) { } } - val storedGroups = ContactsHelper(activity).getStoredGroupsSync() + val storedGroups = ContactsHelper(context).getStoredGroupsSync() - return activity.getEmptyContact().apply { + return context.getEmptyContact().apply { id = localContact.id!! prefix = localContact.prefix firstName = localContact.firstName