安卓kotiln 打开手机相册
时间: 2024-09-25 08:10:37 浏览: 45
在Android Kotlin中,要打开手机相册,你可以使用系统的`ACTION_PICK`或`ACTION_GET_CONTENT` intent。首先,你需要导入相关的权限并创建一个Intent:
```kotlin
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity(), ActivityResultContracts.PickImageCallback {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val openGalleryButton = findViewById<Button>(R.id.open_gallery_button)
openGalleryButton.setOnClickListener {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE)
return
}
val pickImageIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(pickImageIntent, REQUEST_IMAGE_PICK)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_IMAGE_PICK -> {
if (resultCode == RESULT_OK && data != null) {
val imageUri = data.data
// 这里可以处理选中的图片,比如显示在一个ImageView或下载到本地
Toast.makeText(this, "Selected Image: ${imageUri}", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "No image selected", Toast.LENGTH_SHORT).show()
}
}
else -> {
super.onActivityResult(requestCode, resultCode, data)
}
}
}
private const val MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 100
}
```
在这个例子中,我们检查了存储权限,并在用户同意后启动了一个选择图片的activity。当用户从相册选择完图片后,我们会收到回调并获取所选图片的uri。
阅读全文