10

我不知道为什么会发生这种情况,但我无法从 Google 照片提供商那里挑选图片。在 API 27 上进行测试。

使用 ACTION_GET_CONTENT

如果我使用:

val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
  • 我可以在提供商中看到 Google 相册
  • 我可以浏览到一些图片并选择它
  • 然后我被引导回提供者列表(而不是我的应用程序),就好像提供者在 try-catch 中崩溃了一样

当我打开照片提供程序并浏览文件夹时,我会看到很多:

2019-03-02 12:04:15.164 17641-13395/? W/NetworkManagementSocketTagger: untagSocket(120) failed with errno -22
2019-03-02 12:04:22.528 13217-13217/? E/ResourceType: Style contains key with bad entry: 0x01010586
2019-03-02 12:04:22.535 13217-13217/? W/ResourceType: For resource 0x7f020366, entry index(870) is beyond type entryCount(468)

当我点击图片时,我看到了这些:

2019-03-02 12:04:34.150 13217-13217/? W/ResourceType: For resource 0x7f02036c, entry index(876) is beyond type entryCount(468)
2019-03-02 12:04:34.151 13217-13217/? W/ResourceType: For resource 0x7f02036c, entry index(876) is beyond type entryCount(468)
2019-03-02 12:04:34.229 2907-16891/? W/MediaExtractor: FAILED to autodetect media content.
2019-03-02 12:04:34.569 10839-10839/? W/ResourceType: ResTable_typeSpec entry count inconsistent: given 468, previously 1330

使用 ACTION_OPEN_DOCUMENT

在这种情况下,我什至在提供程序抽屉中都看不到 Google 相册。

问题

我该如何解决这个问题,最好使用 ACTION_GET_CONTENT?

4

4 回答 4

4

编辑 2

我想我找到了问题的解决方案。Google 文档中提到访问共享文件将为您提供URI

服务器应用程序将文件的内容 URI 在 Intent 中发送回客户端应用程序。此 Intent 在其 onActivityResult() 的覆盖中传递给客户端应用程序。一旦客户端应用程序获得了文件的内容 URI,它就可以通过获取其 FileDescriptor 来访问该文件。

下面是我在onActivityResult中使用的更新代码。确保最后调用 onActivityResult 的超级方法。

super.onActivityResult(requestCode, resultCode, data)

工作代码

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
data?.data?.let {
    util._log(TAG, it.toString())
}
if (data!!.data != null && data.data != null) {
    try {

        val stream = if (data.data!!.toString().contains("com.google.android.apps.photos.contentprovider")) {
            val ff = contentResolver.openFileDescriptor(data.data!!, "r")
            FileInputStream(ff?.fileDescriptor)
        } else {
            contentResolver.openInputStream(data.data!!)
        }
        val createFile = createImageFile()
        util.copyInputStreamToFile(stream, createFile)
        selectedImagePath = createFile.absolutePath

    } catch (e: Exception) {
        util._log(TAG, Log.getStackTraceString(e))
    }
}
    super.onActivityResult(requestCode, resultCode, data)
}

编辑

还要检查这个stackoverflow帖子

原来的

我在我的 Redmi 6 pro 手机上的 Android oreo 8.1.0(API 27)上使用它,它工作正常。

你还没有发布onActivityResult方法可能是你需要做一些修改的地方。我都试过了

下面是我的代码片段

val pickIntent = Intent(Intent.ACTION_VIEW)
pickIntent.type = "image/*"
pickIntent.action = Intent.ACTION_GET_CONTENT
pickIntent.addCategory(Intent.CATEGORY_OPENABLE)

startActivityForResult(pickIntent, SELECT_PICTURE)

onActivityResult我像这样解析它

if (data!!.data != null && data.data != null) {
    try {
        //                    CommonUtilities._Log(TAG, "Data Type " + data.getType());
        if (!isFinishing) {
            val inputStream = contentResolver.openInputStream(data.data!!)
            val createFile = createImageFile()
            copyInputStreamToFile(inputStream!!, createFile)
            //                        CommonUtilities._Log(TAG, "File Path " + createFile.getAbsolutePath());
            selectedImagePath = createFile.absolutePath
        }
    } catch (e: IOException) {
        util._log(TAG, Log.getStackTraceString(e))
    }
}

创建新文件的方法

@Throws(IOException::class)
private fun createImageFile(): File {
    // Create an image file name
    val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(Date())
    val imageFileName = "yesqueen_" + timeStamp + "_"
    val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
    return File.createTempFile(imageFileName, ".jpg", storageDir)
}

从输入流中读取的方法

fun copyInputStreamToFile(`in`: InputStream, file: File) {
    var out: OutputStream? = null
    try {
        out = FileOutputStream(file)
        val buf = ByteArray(1024)
        var len: Int = 0
        while (`in`.read(buf).apply { len = this } > 0) {
            out.write(buf, 0, len)
        }

        /*while (`in`.read(buf).let {
                    len = it
                    true
                }) {
            out.write(buf, 0, len)
        }*/
        /* while ((len = `in`.read(buf)) > 0) {
             out.write(buf, 0, len)
         }*/
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        try {
            out?.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        try {
            `in`.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }
}
于 2019-03-05T10:42:53.897 回答
1

我有同样的问题,我无法从谷歌照片中获取图像 URI ACTION_GET_CONTENT。问题与launchMode我的活动有关。我找不到任何对 Android 文档的引用。但这样问题就完全解决了:

我有一个单一的活动应用程序,我的ACTION_GET_CONTENT意图是这样的:

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

问题是singleInstanceAndroidManifest.xml 中活动定义中的启动模式。

<activity
android:name=".ui.MainActivity"
android:configChanges="orientation"
android:launchMode="singleInstance"
android:screenOrientation="portrait"
android:theme="@style/AppTheme"
android:windowSoftInputMode="adjustResize|stateHidden"/>

通过删除 android:launchMode 行,问题得到解决。如果您的活动需要singleInstance,创建一个虚拟活动将是一个很好的解决方案。在这里,您可以为结果启动一个虚拟活动,然后在其中执行您的 Intent 内容onCreate,然后setResult()执行您请求的活动:

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()
    }
}

这是您在 MainActivity 中的代码:

gallery.setOnClickListener {
    startActivityForResult(
        Intent(requireActivity(), ImagePickerActivity::class.java),
        GALLERY_RESULT
    )
}
于 2020-10-10T07:25:02.860 回答
1

我已经用这段代码完成了。

val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
startActivityForResult(intent,100)

和结果

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        100 -> {
            if (resultCode == Activity.RESULT_OK) {
                val bitmap = generateBitmap(this,data!!.data)
                //TODO show bitmap to your View
                showPicture(bitmap!!)
            }
        }
    }
}

generateBitmap(context,uri)Kotlin 中的方法

fun generateBitmap(context: Context, uri: Uri): Bitmap? {
    var filePath = ""
    var cursor: Cursor?
    var columnIndex = 0
    try {
        val column = arrayOf(MediaStore.Images.Media.DATA)
        val sel = arrayOf(MediaStore.Images.Media._ID + "=?")
        if (uri.toString().startsWith("content://com.google.android.apps.photos.contentprovider")){
            val content = this.contentResolver.openInputStream(uri) ?: return null
            val pictureBitmap = BitmapFactory.decodeStream(content)
            return pictureBitmap
        } else {
            filePath = ""
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                val wholeID = DocumentsContract.getDocumentId(uri)
                val id = arrayOf(wholeID.split(":")[1])
                cursor = context.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel[0], id, null)
                columnIndex = cursor.getColumnIndex(column[0])
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(columnIndex)
                }
                cursor.close()
            } else {
                val cursorLoader = CursorLoader(context, uri, column, null, null, null)
                val cursor = cursorLoader.loadInBackground()
                if (cursor != null) {
                    var column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                    cursor.moveToFirst()
                    filePath = cursor.getString(column_index)
                }
            }
            //TODO generate bitmap from file path
            return bitmap(filePath)
        }
    } catch (e: Exception) {
        print(e.message)
    }
    return null
}

对于文件路径中的getBitmap,我使用了这种方法

 fun bitmap(path : String) : Bitmap{
    val image = File(path)
    val bmOptions = BitmapFactory.Options()
    return BitmapFactory.decodeFile(image.absolutePath, bmOptions)
}
于 2019-03-11T11:46:04.140 回答
0

ACTION_PICK将提供选择图像的选项,您可以获得文件路径

    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Image.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");

                Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
                sIntent.addCategory(Intent.CATEGORY_DEFAULT);
                sIntent.setType("image/*");

                Intent chooserIntent;
                if (getPackageManager().resolveActivity(sIntent, 0) != null) {
                    // it is device with samsung file manager
                    chooserIntent = Intent.createChooser(sIntent, "Select file");
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{intent});
                } else {
                    chooserIntent = Intent.createChooser(intent, "Select file");
                }
                try {
                    startActivityForResult(chooserIntent, REQUEST_TAKE_GALLERY_VIDEO);
                } catch (android.content.ActivityNotFoundException ex) {
                    Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
                }
于 2019-03-04T11:29:36.437 回答