-1

I've got the following data class:

data class Contact(
        val id : String,
        val name : String,
        val number : String)

I now want to add a Contact to the Contact list of the phone using a method inside a BoundService. I've got the following code right now:

fun importContact(Contact: Contact) {
        val intent = Intent(ContactsContract.Intents.Insert.ACTION)
        intent.type = ContactsContract.RawContacts.CONTENT_TYPE
        intent.putExtra(ContactsContract.Intents.Insert.NAME, Contact.name)
        intent.putExtra(ContactsContract.Intents.Insert.PHONE, Contact.number)
        startActivity(intent)
    }

However as this method is run inside a BoundService it throws me the following Exception: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

How can I solve this problem?

Felixkruemel
  • 434
  • 1
  • 4
  • 17

1 Answers1

1

It's as easy as adding this to it:

intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK

Somehow I didn't even try the suggested solution in the error.

So whole code needs to look like this:

fun importContact(Contact: Contact) {
        val intent = Intent(ContactsContract.Intents.Insert.ACTION)
        intent.type = ContactsContract.RawContacts.CONTENT_TYPE
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.putExtra(ContactsContract.Intents.Insert.NAME, Contact.name)
        intent.putExtra(ContactsContract.Intents.Insert.PHONE, Contact.number)
        startActivity(intent)
    }
Felixkruemel
  • 434
  • 1
  • 4
  • 17
  • 1
    is this really useful then ? i mean, you had code which gave you an explicit suggestion on how to fix it, which you then applied and now it's working... – a_local_nobody Mar 03 '22 at 12:44