没有为读取联系人调用onActivityResult

时间:2018-10-07 20:53:33

标签: android kotlin startactivityforresult

我正在尝试阅读和显示TextView上的联系人。问题是,我可以启动“联系人”活动并选择联系人。之后,父活动(启动了联系人活动)消失了。为什么不起作用?

class MainActivity : AppCompatActivity() {
    val REQUEST_CONTACT = 1000

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        takeContact.setOnClickListener {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
                launchContactPicker()

            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
                } else {
                    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS), REQUEST_CONTACT)
                }

            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            REQUEST_CONTACT -> {
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    launchContactPicker()
                } else {
                    Toast.makeText(this, "Permission denied. You can't read contacts!", Toast.LENGTH_LONG).show()
                }
                return
            }
        }
    }

    private fun launchContactPicker() {
        Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI).also { intent ->
            intent.resolveActivity(packageManager)?.also {
                startActivityForResult(intent, REQUEST_CONTACT)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        if (requestCode == REQUEST_CONTACT && resultCode == RESULT_OK) {
            val uri = data.data as Uri
            val projection = arrayOf(ContactsContract.CommonDataKinds.Phone.NUMBER)
            val cursor = contentResolver.query(uri, projection, null, null, null)
            if (cursor != null && cursor.moveToFirst()) {
                val phoneIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                val nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)

                val number = cursor.getString(phoneIdx)
                val name = cursor.getString(nameIdx)
                val contact = "$name\n$number"

                selectedContact.text = contact

            }

            cursor.close()
        }
    }
}

我也已经通过调试器进行检查,未达到onActivityResult。我已经在Android 6上进行了测试。

0 个答案:

没有答案