ActivityResultContracts应用 companion object { private const val MIME_AUDIO = "audio*" }一. startActivityForResult 替代
startActivityForResult 过期的替代方法
private val launcherActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { val code = it.resultCode val data = it.data } fun onTakePhoto(view : View) { // 跳转Activity launcherActivity.launch(Intent(this, CameraActivity::class.java)) }二. 权限申请
- 单个权限申请
private val requestPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { if (it) { // 授权权限成功 } else { // 授权失败 val shouldRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.CAMERA ) if (shouldRequestPermission) { // 当次拒绝了权限申请,可以显示请求许可理由,让用户重新授权 } else { // 用户拒绝权限授权,并且点了“不再询问”权限 } } } fun requestPermission(view : View) { // 请求权限 requestPermission.launch(Manifest.permission.CAMERA) }
- 多个权限申请
val requestsPermissions = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions()) {params : MutableMap三. 录像-> // 已经通过的权限列表 val grantedList = params.filterValues { it }.mapNotNull { it.key } // 是否所有权限都通过 val allGranted = grantedList.size == params.size if (allGranted) { // 所有权限都通过了 } else { val list = (params - grantedList).map { it.key } //未通过的权限 val deniedList = list.filter {ActivityCompat.shouldShowRequestPermissionRationale(activity, it)} Log.i(TAG, "当次拒绝了权限申请,可以显示请求许可理由,让用户重新授权 : ${deniedList}") //拒绝并且点了“不再询问”权限 val alwaysDeniedList = list - deniedList Log.i(TAG, "拒绝并且点了“不再询问”权限 : ${alwaysDeniedList}") } } fun requestMulPermissions(view : View) { // 请求权限 requestsPermissions.launch( arrayOf( Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_ConTACTS ) ) }
- 首先要在AndroidManifest.xml中的 application节点下添加 provider
... ...
- 开始录像
var takeVideoContracts = registerForActivityResult(ActivityResultContracts.CaptureVideo()) { // it : Boolean? 录像成功或失败 } fun startTakeVideo(view : View) { try { val root = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "media") if (!root.exists()) { root.mkdir() } // 录像成功之后,录像文件所在位置 var mp4Path = File(root, "${System.currentTimeMillis()}.mp4") var fileUri = FileProvider.getUriForFile( this, "${packageName}.fileprovider",, mp4Path) takeVideoContracts.launch(fileUri) } catch (ex : Exception) { ex.printStackTrace() } }四. 拍照
- 高清拍照
val pictureContracts = registerForActivityResult(ActivityResultContracts.TakePicture()) {result : Boolean -> if (result) { Glide.with(this).load(imageSaveUri).into(mBinding.ivPicture) } } var imageSaveUri : Uri? = null fun onTakePicture(view : View) { imageSaveUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val values = ContentValues() values.put(MediaStore.MediaColumns.DISPLAY_NAME, "图片名称.jpg") values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES) contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) } else { FileProvider.getUriForFile( this, "${packageName}.fileprovider", File(externalCacheDir!!.absolutePath, "图片名称.jpg") ) } pictureContracts.launch(imageSaveUri) }
- 拍摄预览图片(比较模糊)
val previewContracts = registerForActivityResult( ActivityResultContracts.TakePicturePreview()) { bitmap : Bitmap? -> bitmap?.also { Glide.with(this).load(it).into(mBinding.ivPicture) } } fun onTakePicturePreview(view : View) { previewContracts.launch(null) }五. 获取手机联系人
- 获取一个联系人
val contactContracts = registerForActivityResult(ActivityResultContracts.PickContact()) { uri : Uri? -> //如果Uri为null,说明用户没有 *** 作直接返回,这里代码会在下面补贴出来,因为涉及跨进程交互,代码比较长,不想贴这里影响阅读效率 if (uri != null) { val contactByUri:ContactItem? = PickContactUtils.getContactByUri(this, uri) } } fun onReadContact(view : android.view.View) { contactContracts.launch(null) }
- 获取所有联系人
var contactItems : ArrayList= PickContactUtils.onAllContact(this)
下方为工具类
import android.content.Context import android.database.Cursor import android.net.Uri import java.util.* import kotlin.collections.ArrayList import android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI import android.provider.ContactsContract.CommonDataKinds.Phone.CONTACT_ID import android.provider.ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME import android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER import android.provider.ContactsContract.Contacts._ID object PickContactUtils { private var TAG = javaClass.simpleName fun getContactByUri(context : Context, uri : Uri) : ContactItem? { var cursor : Cursor? = null; try { cursor = context.getContentResolver().query(uri, null, null, null, null) cursor?.apply { moveToFirst(); var contact_name = getString(getColumnIndex(DISPLAY_NAME)) var contact_id = getString(getColumnIndex(_ID)) var phone = context.getContentResolver().query( CONTENT_URI, null, CONTACT_ID + " = " + contact_id, null, null ) phone?.apply { var phones = arrayListOf六. 从文件管理器选择文件() while (moveToNext()) { getString(getColumnIndex(NUMBER))?.replace("+86", "") ?.replace("+ 86", "") ?.replace("-", "") ?.replace(" ", "") ?.also { phones.add(it) } } return ContactItem(contact_id, contact_name, phones) } } } catch (e : Exception) { e.printStackTrace() } finally { cursor?.close() } return null } fun onAllContact(context : Context) : ArrayList { var contacts = ArrayList () var cursor : Cursor? = null; try { cursor = context.getContentResolver().query( CONTENT_URI, null, null, null, null ) cursor?.apply { moveToFirst(); while (moveToNext()) { var contact_name = getString(getColumnIndex(DISPLAY_NAME)) var contact_Id = getString(getColumnIndex(CONTACT_ID)) var phone = context.getContentResolver() .query(CONTENT_URI, null, CONTACT_ID + " = " + contact_Id, null, null) phone?.apply { var phones = arrayListOf () while (moveToNext()) { getString(getColumnIndex(NUMBER))?.replace("+86", "") ?.replace("+ 86", "") ?.replace("-", "") ?.replace(" ", "") ?.also { phones.add(it) } } var ishad = false for (item in contacts) { if (item.contact_id == contact_Id) { ishad = true } } if (!ishad) { contacts.add(ContactItem(contact_Id, contact_name, phones)) } } } Collections.sort(contacts, ContactComparator()) } } catch (e : Exception) { e.printStackTrace(); } finally { cursor?.close(); } return contacts } } class ContactItem(var contact_id : String?, var contact_name : String?, var contact_phones : ArrayList ) { } class ContactComparator : Comparator { override fun compare(contact1 : ContactItem, contact2 : ContactItem) : Int { var contact_id1 = contact1.contact_id var contact_id2 = contact2.contact_id if (contact_id1 != null && contact_id2 != null) { return contact_id1.compareTo(contact_id2) } return -1 } }
- 选择一个目录
var opendocumentTreeActivity = registerForActivityResult(ActivityResultContracts.OpendocumentTree()) { uri: Uri -> Log.i(TAG, "选择一个目录 OpendocumentTree() :: $uri") } opendocumentTreeActivity.launch(null)
- 选择文件 GetContent()
var getContentActivity = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri -> Log.i(TAG, "获取一个文件 GetContent() :: $uri") contentResolver.openInputStream(uri)?.apply { try { var br = BufferedReader(InputStreamReader(this, "utf-8")) var sb = StringBuilder() for (line in br.readLines()) { sb.append(line).append("n") } mBinding.tvMsg.text = sb.toString() } catch (e: Exception) { e.printStackTrace() } } } getContentActivity.launch(MIME_TEXT)
- 选择文件 Opendocument()
var opendocumentActivity = registerForActivityResult(ActivityResultContracts.Opendocument()) { uri: Uri -> Log.i(TAG, "选择一个文件 Opendocument() :: $uri") contentResolver.openInputStream(uri)?.apply { try { var br = BufferedReader(InputStreamReader(this, "utf-8")) var sb = StringBuilder() for (line in br.readLines()) { sb.append(line).append("n") } mBinding.tvMsg.text = sb.toString() } catch (e: Exception) { e.printStackTrace() } } } opendocumentActivity.launch(arrayOf(MIME_TEXT))
- 获取一个或多个文件 GetMultipleContents()
var getMultipleContents = registerForActivityResult(ActivityResultContracts.GetMultipleContents()) { it: List-> Log.i(TAG, "获取一个或多个文件 GetMultipleContents() :: $it") mBinding.tvMsg.text = it.toString() } getMultipleContents.launch(MIME_TEXT)
- 获取一个或多个文件 OpenMultipledocuments()
var openMultipledocumentsActivity = registerForActivityResult(ActivityResultContracts.OpenMultipledocuments()) { it: List-> Log.i(TAG, "选择多个文件 OpenMultipledocuments() :: $it") mBinding.tvMsg.text = it.toString() } openMultipledocumentsActivity.launch(arrayOf(MIME_IMAGE))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)