Pick from Google Photos provider with ACTION_GET_CONTENT or OPEN_DOCUMENT

后端 未结 4 1981
死守一世寂寞
死守一世寂寞 2021-01-17 18:33

I have no clue at why this happens, but I am not able to pick images from the Google Photos provider. Testing on API 27.

With ACTION_GET_CONTENT

If I use:<

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-17 18:59

    I had the same problem, I could not get image URI from Google Photos with a ACTION_GET_CONTENT intent. The problem was related to launchMode of my activity. I could not find any reference to Android documentations. but this way the problem completely solved:

    I had a single activity application and my ACTION_GET_CONTENT intent was something like this:

    val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
          type = "image/*"
    }
    startActivityForResult(intent, GALLERY_RESULT)
    

    the problem was singleInstance launch mode in activity's definition in AndroidManifest.xml.

    
    

    By removing the android:launchMode line the problem was solved. If your activity needs to be singleInstance, creating a dummy activity will be a good solution. here you can start a dummy activity for result and then do your Intent stuff inside its onCreate and then setResult() for your requested activity:

    class ImagePickerActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
                type = "image/*"
            }
    
            if (intent.resolveActivity(packageManager!!) != null) {
                startActivityForResult(intent, GALLERY_RESULT)
            } else {
                Toast.makeText(
                    this,
                    "No Gallery APP installed",
                    Toast.LENGTH_LONG
                ).show()
                finish()
            }
    
        }
    
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
            //here data is resulted URI from ACTION_GET_CONTENT
            //and we pass it to our MainActivy using setResult
            setResult(resultCode, data)
            finish()
        }
    }
    

    and here is your code in your MainActivity:

    gallery.setOnClickListener {
        startActivityForResult(
            Intent(requireActivity(), ImagePickerActivity::class.java),
            GALLERY_RESULT
        )
    }
    

提交回复
热议问题