最常用的写法
registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
val data = result.data
val resultCode= result.resultCode
val extra = data?.getStringExtra("extra")
}.launch(Intent(this, MainActivity::class.java))
除了基本用法,ActivityResultContracts还提供了一些ActivityResultContract的实现类,以便进行其他的操作:
- RequestMultiplePermissions : 多个权限请求
- RequestPermission : 单个权限请求
- TakePicturePreview : 拍照预览
- TakePicture : 拍照
- TakeVideo : 摄像
- PickContact : 选择联系人
- GetContent : 获取各种文件的Uri
- GetMultipleContents : 获取多个各种文件的Uri
- OpenDocument : 打开文件
- OpenMultipleDocuments : 打开多个文件
- OpenDocumentTree : 打开文件夹
- CreateDocument : 创建文件
打开相机拍照:
registerForActivityResult(ActivityResultContracts.TakePicturePreview()){
// 返回bitmap
}.launch(null)
获取单个/多个权限请求:
// 单个权限获取
registerForActivityResult(ActivityResultContracts.RequestPermission()) {
if (it) {//同意权限
} else {//拒绝权限
}
}.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
// 多个权限获取
var permissions: Array<String> = arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
)
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
if (it[Manifest.permission.WRITE_EXTERNAL_STORAGE]!!) {// 同意
} else {// 拒绝
}
if (it[Manifest.permission.CAMERA]!!) {// 同意
} else {// 拒绝
}
}.launch(permissions)
查询联系人信息:
registerForActivityResult(ActivityResultContracts.PickContact()){
if(it != null){
val cursor = contentResolver.query(it, null, null, null, null)
cursor?.run {
if(cursor.moveToFirst()){
val name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
}
}
}
}.launch(null)
选取文件:
registerForActivityResult(ActivityResultContracts.OpenDocument()){
// 获取的文件uri
}.launch(arrayOf("image/*","text/plain"))
评论