moving some Activity extension responsibilities to Context

This commit is contained in:
tibbi 2018-11-28 21:52:38 +01:00
parent f96f2bca22
commit 7c0661983d
5 changed files with 215 additions and 219 deletions

View File

@ -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'

View File

@ -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<Contact>) {
val file = getTempFile()
@ -117,96 +106,6 @@ fun BaseSimpleActivity.shareContacts(contacts: ArrayList<Contact>) {
}
}
fun BaseSimpleActivity.sendSMSToContacts(contacts: ArrayList<Contact>) {
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<Contact>) {
val emails = ArrayList<String>()
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<Contact>, groupId: Long) {
val publicContacts = contacts.filter { it.source != SMT_PRIVATE }.toMutableList() as ArrayList<Contact>
val privateContacts = contacts.filter { it.source == SMT_PRIVATE }.toMutableList() as ArrayList<Contact>
if (publicContacts.isNotEmpty()) {
ContactsHelper(this).addContactsToGroup(publicContacts, groupId)
}
if (privateContacts.isNotEmpty()) {
LocalContactsHelper(this).addContactsToGroup(privateContacts, groupId)
}
}
fun BaseSimpleActivity.removeContactsFromGroup(contacts: ArrayList<Contact>, groupId: Long) {
val publicContacts = contacts.filter { it.source != SMT_PRIVATE }.toMutableList() as ArrayList<Contact>
val privateContacts = contacts.filter { it.source == SMT_PRIVATE }.toMutableList() as ArrayList<Contact>
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<String> {
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<String>
sourceNames.removeAll(config.ignoredContactSources)
return sourceNames
}
fun SimpleActivity.contactClicked(contact: Contact) {
when (config.onContactClick) {
ON_CLICK_CALL_CONTACT -> callContact(contact)

View File

@ -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<Contact>) {
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<Contact>) {
val emails = ArrayList<String>()
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<Contact>, groupId: Long) {
val publicContacts = contacts.filter { it.source != SMT_PRIVATE }.toMutableList() as ArrayList<Contact>
val privateContacts = contacts.filter { it.source == SMT_PRIVATE }.toMutableList() as ArrayList<Contact>
if (publicContacts.isNotEmpty()) {
ContactsHelper(this).addContactsToGroup(publicContacts, groupId)
}
if (privateContacts.isNotEmpty()) {
LocalContactsHelper(this).addContactsToGroup(privateContacts, groupId)
}
}
fun Context.removeContactsFromGroup(contacts: ArrayList<Contact>, groupId: Long) {
val publicContacts = contacts.filter { it.source != SMT_PRIVATE }.toMutableList() as ArrayList<Contact>
val privateContacts = contacts.filter { it.source == SMT_PRIVATE }.toMutableList() as ArrayList<Contact>
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<String> {
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<String>
sourceNames.removeAll(config.ignoredContactSources)
return sourceNames
}

View File

@ -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<String>()
fun getContacts(callback: (ArrayList<Contact>) -> Unit) {
Thread {
val contacts = SparseArray<Contact>()
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<Contact>(contactsSize)
val resultContacts = ArrayList<Contact>(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<Contact>
@ -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<ContactSource>()
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<Contact>) {
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<Group>, contactId: Int? = null): SparseArray<ArrayList<Group>> {
val groups = SparseArray<ArrayList<Group>>()
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<Group>) -> 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<Group> {
val groups = getDeviceStoredGroups()
groups.addAll(activity.groupsDB.getGroups())
groups.addAll(context.groupsDB.getGroups())
return groups
}
fun getDeviceStoredGroups(): ArrayList<Group> {
val groups = ArrayList<Group>()
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<ContactSource> {
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<ContactSource> {
val sources = LinkedHashSet<ContactSource>()
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<ContentProviderOperation>): ArrayList<ContentProviderOperation> {
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<ContentProviderResult>
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<Contact>) {
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<Contact>) {
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<Contact>, 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<Contact>) {
val localContacts = contacts.filter { it.source == SMT_PRIVATE }.map { it.id }.toTypedArray()
LocalContactsHelper(activity).deleteContactIds(localContacts)
LocalContactsHelper(context).deleteContactIds(localContacts)
try {
val operations = ArrayList<ContentProviderOperation>()
@ -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<RecentCall>) -> Unit) {
Thread {
val calls = ArrayList<RecentCall>()
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()
}

View File

@ -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<Contact>
class LocalContactsHelper(val context: Context) {
fun getAllContacts() = context.contactsDB.getContacts().map { convertLocalContactToContact(it) }.toMutableList() as ArrayList<Contact>
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<Contact>, 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<Int>) {
ids.forEach {
activity.contactsDB.deleteContactId(it)
context.contactsDB.deleteContactId(it)
}
}
fun toggleFavorites(ids: Array<Int>, 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