registerForActivityResult常规用法
随时调用 无需提前注册(推荐)
//跳转
activityResultRegistry.register("456",ActivityResultContracts.StartActivityForResult()){result->
if (result?.resultCode != Activity.RESULT_OK) return@register
}.run { launch(Intent(this@Activity, CaptureActivity::class.java)) }
//获取权限
activityResultRegistry.register("123", ActivityResultContracts.RequestPermission()){
if (!it) return@register
}.run { launch(Manifest.permission.CAMERA) }
registerForActivityResult常规用法 (不推荐)
使用registerForActivityResult方法来注册回调。
此方法简化数据回调的写法,并且提供了多种用途。
java
//onCreate中注册、或者成员变量
ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
//
}
});
launcher.launch(intent);
//权限
var registerPermission: ActivityResultLauncher<String>? = null
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
//相机权限返回
registerPermission = activityResultRegistry.register("CAMERA", ActivityResultContracts.RequestPermission()) {
//同意权限
if (it) { }
}
}
})
//调用相机权限
registerPermission?.launch(Manifest.permission.CAMERA)
kotlin
//onCreate中注册
val register = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data = result.data
val extra = data?.getStringExtra("extra")
}
}
register.launch(Intent(this, MainActivity::class.java))
【注意】:registerForActivityResult只能在onCreate中注册。onstart之后就不能注册了
除了基本用法,ActivityResultContracts还提供了一些ActivityResultContract的实现类,以便进行其他的操作:
RequestMultiplePermissions | 多个权限请求 |
---|---|
RequestPermission | 单个权限请求 |
TakePicturePreview | 拍照预览 |
TakePicture | 拍照 |
TakeVideo | 摄像 |
PickContact | 选择联系人 |
GetContent | 获取各种文件的Uri |
GetMultipleContents | 获取多个各种文件的Uri |
OpenDocument | 打开文件 |
OpenMultipleDocuments | 打开多个文件 |
OpenDocumentTree | 打开文件夹 |
CreateDocument | 创建文件 |
打开相机拍照:
//--------------------------模糊--------------------------
activityResultRegistry.register("789", ActivityResultContracts.TakePicturePreview()) {bitmap->
bitmap?.let {
YImageDialog.show(bitmap)
YLog.i("分辨率:${bitmap.width}x${bitmap.height} 路径:${file} uri:${uri}")
}
}.run { launch(null) }
//--------------------------高清--------------------------
val file = File(getExternalFilesDir("")!!.absolutePath + "/img/1.jpg")
if (!file.parentFile.exists()) file.parentFile.mkdirs()
val uri: Uri = FileProvider.getUriForFile(this, applicationContext.packageName + ".fileProvider", file)
//拍照
activityResultRegistry.register("789", ActivityResultContracts.TakePicture()) {
if (!it) return@register //拍照失败
val bitmap = YUri.getBitmap(this, uri)
YImageDialog.show(bitmap)
YLog.i("分辨率:${bitmap.width}x${bitmap.height} 路径:${file} uri:${uri}")
}.run { launch(uri) }
打开相机拍照并且剪切
//拍照并返回,详细看YTake源码
YTake.takeAndCorp(this) {
val bitmap = YConvert.uri2Bitmap(this, it)
YImageDialog.show(bitmap)
}
自定义返回格式
/*
用法:
//拍照返回
private val takeImage = registerForActivityResult(YTakePicture(this)) {
//it=Uri
}
//拍照
val file = File(YPath.getPICTURES() + "/img/${Date().time}.jpg")
takeImage.launch(file)
*/
/**
* 拍照,传入File,拍照成功返回Uri
*/
class YTakePicture(val context: Context) : ActivityResultContract<File, Uri>() {
var uri: Uri? = null
override fun createIntent(context: Context, input: File?): Intent {
uri = YPicture.createImageUri(context, input)
return Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, uri)
}
override fun parseResult(resultCode: Int, intent: Intent?): Uri? {
if (resultCode != Activity.RESULT_OK) return null
return uri
}
}
打开相机录像
//视频路径
val file = File(YPath.get() + "/img/1.mp4")
if (!file.parentFile.exists()) file.parentFile.mkdirs()
val uri: Uri = FileProvider.getUriForFile(this, applicationContext.packageName + ".fileProvider", file)
//录像
val registerTakeVideo = registerForActivityResult(ActivityResultContracts.TakeVideo()) {
//测试缩略图为空 it:Bitmap=null
YLog.i(" 路径:${file} uri:${uri}")
}
//单个权限获取
val registerPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
//同意权限
if (it) registerTakeVideo.launch(uri)
}
registerPermission.launch(Manifest.permission.CAMERA)
获取单个/多个权限请求:
// 单个权限获取
activityResultRegistry.register("123", ActivityResultContracts.RequestPermission()){
if (!it) return@register
}.run { launch(Manifest.permission.WRITE_EXTERNAL_STORAGE) }
// 多个权限获取
var permissions = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO)
val registerPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
for (item in permissions) {
if (it[item]!!) {// 同意
Log.d(TAG, "获取到权限:${permissions}")
} else {
Toast.makeText(this, "用户未授予的权限。", Toast.LENGTH_SHORT).show()
return@registerForActivityResult
}
}
//获取所有权限后
startCamera()
}
//申请权限
registerPermissions.launch(permissions)
查询联系人信息:
val register = 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))
}
}
}
}
register.launch(null)
选取文件:
val register = registerForActivityResult(ActivityResultContracts.OpenDocument()){
// 获取的文件uri
}
register.launch(arrayOf("image/*","text/plain"))
//或者
var register: ActivityResultLauncher<Array<String>>? = null
lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
register = activityResultRegistry.register("chose", ActivityResultContracts.OpenDocument()) { it: Uri? ->
// 获取的文件uri
}
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
register?.unregister()
}
})
register?.launch(arrayOf("image/jpg", "image/jpeg", "image/png",))