首页 > 解决方案 > 使用 FileProvider 从图库中拍照

问题描述

我想从画廊上传一张照片。当我通过内置模拟器检查此代码时,此代码有效。但是当我连接我的手机(小米红米 Note 7)时,此代码停止工作。请帮忙。提供者:

 <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.example.test.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/files"/>
    </provider>

文件.xml

<paths>
<files-path
    name="testPhoto"
    path="."/>

科特林:

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    imageView3 = findViewById(R.id.imageView3)
    

    val intent: Intent =
        Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
    intent.flags = Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
    photo = File(this.applicationContext.filesDir,"photo.jpg")
    val uri = FileProvider
        .getUriForFile(this, "com.example.test.fileprovider", photo)
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
    startActivityForResult(intent, 2)
    
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    when{
        resultCode != Activity.RESULT_OK -> return
        requestCode == 2 -> {

            if (photo.exists()) {
                val bitmap = BitmapFactory.decodeFile(photo.path)
                imageView3.setImageBitmap(bitmap)
            } else {
                Toast.makeText(this,"error",Toast.LENGTH_SHORT).show()
                imageView3.setImageDrawable(null)
            }
        }

    }
    super.onActivityResult(requestCode, resultCode, data)
}

标签: androidkotlinuriandroid-fileprovider

解决方案


推荐阅读