热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

安卓中如何使用相机拍照

效果图
效果图
安卓中如何使用相机拍照
主要代码

class MainActivity : AppCompatActivity() { private lateinit var uri: Uri private lateinit var cameraSavePath: File override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener { applyPermissionAndPhoto() } } private fun applyPermissionAndPhoto() { SoulPermission.getInstance() .checkAndRequestPermissions( Permissions.build( Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE ), object : CheckRequestPermissionsListener { override fun onAllPermissionOk(allPermissions: Array?) { photo() } override fun onPermissionDenied(refusedPermissions: Array?) { } }) } private fun photo() { cameraSavePath = File( Environment.getExternalStorageDirectory(), System.currentTimeMillis().toString() + ".jpg" ) val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) initUriToSaveImage(intent) intent.putExtra(MediaStore.EXTRA_OUTPUT, uri) startActivityForResult(intent, 1) } private fun initUriToSaveImage(intent: Intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile( this, "$packageName.file_provider", cameraSavePath ) intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } else { uri = Uri.fromFile(cameraSavePath) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { val photoPath: String? if (requestCode == 1 && resultCode == RESULT_OK) { photoPath = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { cameraSavePath.toString() } else { uri.encodedPath } photoPath?.let { Glide.with(this).load(it).into(imageView) } } super.onActivityResult(requestCode, resultCode, data) } } 完整源代码

https://gitee.com/cxyzy1/camera_album_demo


推荐阅读
author-avatar
蒋雨儿_824
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有