美文网首页安卓开发
安卓中如何访问系统相册

安卓中如何访问系统相册

作者: 蓝不蓝编程 | 来源:发表于2020-08-17 09:26 被阅读0次

    效果图

    主要代码

    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            button.setOnClickListener { applyPermissionAndOpenAlbum() }
        }
    
        private fun applyPermissionAndOpenAlbum() {
            SoulPermission.getInstance()
                .checkAndRequestPermissions(
                    Permissions.build(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    ),
                    object : CheckRequestPermissionsListener {
                        override fun onAllPermissionOk(allPermissions: Array<out Permission>?) {
                            openAlbum()
                        }
    
                        override fun onPermissionDenied(refusedPermissions: Array<out Permission>?) {
                        }
                    })
        }
    
        private fun openAlbum() {
            val intent = Intent()
            intent.action = Intent.ACTION_PICK
            intent.type = "image/*"
            startActivityForResult(intent, 2)
        }
    
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            val photoPath: String?
            if (requestCode == 2 && resultCode == RESULT_OK) {
                data?.data?.let {
                    photoPath = UriUtil.getRealPathFromUri(this, it)
                    Glide.with(this).load(photoPath).into(imageView)
                }
            }
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
    

    完整源代码

    https://gitee.com/cxyzy1/camera_album_demo

    相关文章

      网友评论

        本文标题:安卓中如何访问系统相册

        本文链接:https://www.haomeiwen.com/subject/fjpidktx.html