作者:蒋雨儿_824 | 来源:互联网 | 2023-09-24 16:37
效果图
主要代码
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