Android 意图在回调中始终为空(使用 registerForActivityResult)

Android intent always has null in callback (using registerForActivityResult)

我正在使用这段代码,但我遗漏了一些东西,因为几乎一切正常,但当回调响应时,我在数据中得到了一个空值:

private inner class JavascriptInterface {
    @android.webkit.JavascriptInterface
    fun image_capture() {
        val photoFileName = "photo.jpg"
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        var photoFile = getPhotoFileUri(photoFileName)
        if (photoFile != null) {
            fileProvider = FileProvider.getUriForFile(applicationContext, "com.codepath.fileprovider", photoFile!!)
            intent.putExtra(EXTRA_OUTPUT, fileProvider)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            if (intent.resolveActivity(packageManager) != null) {
                getContent.launch(intent)
            }
        }
    }
}

val getContent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
    if (result.resultCode == Activity.RESULT_OK) {
        val intent:Intent? = result.data // <- PROBLEM: data is ALWAYS null
    }
}

我与此相关的清单片段如下所示:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我的 fileprovider.xml 看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path name="images" path="Pictures" />
</paths>

感谢任何帮助。谢谢!

应该是 null,因为 ACTION_IMAGE_CAPTURE is not documented to return a Uri。您正在使用 EXTRA_OUTPUT。图像应存储在您使用 EXTRA_OUTPUT.

指定的位置

不过请注意,您应该将 FLAG_GRANT_READ_URI_PERMISSIONFLAG_GRANT_WRITE_URI_PERMISSION 添加到 Intent,因为相机应用需要能够将图像写入所需位置.

所以,我最终检查了 TakePicture 合同@ian(感谢您的提示!),在拼凑了我发现的各种资源之后,我终于让它工作了。这是 webview Activity:

的相关 kotlin 代码
class WebViewShell : AppCompatActivity() {
    val APP_TAG = "MyApp"

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

        // Storing data into SharedPreferences
        val sharedPreferences = getSharedPreferences("MySharedPrefs", MODE_PRIVATE)
        val storedurl: String = sharedPreferences.getString("url", "").toString()

        val myWebView: WebView = findViewById(R.id.webview_webview)
        myWebView.clearCache(true)

        myWebView.settings.setJavaScriptCanOpenWindowsAutomatically(true)
        myWebView.settings.setJavaScriptEnabled(true)
        myWebView.settings.setAppCacheEnabled(true)
        myWebView.settings.setAppCacheMaxSize(10 * 1024 * 1024)
        myWebView.settings.setAppCachePath("")
        myWebView.settings.setDomStorageEnabled(true)
        myWebView.settings.setRenderPriority(android.webkit.WebSettings.RenderPriority.HIGH)
        WebView.setWebContentsDebuggingEnabled(true)

        myWebView.addJavascriptInterface(JavascriptInterface(),"Android")
        myWebView.loadUrl(storedurl)
    }

    private inner class JavascriptInterface {
        @android.webkit.JavascriptInterface
        fun image_capture() { // opens Camera
            takeImage()
        }
    }
    
    private fun takeImage() {
        try {
            val uri = getTmpFileUri()
            lifecycleScope.launchWhenStarted {
                takeImageResult.launch(uri)
            }
        }
        catch (e: Exception) {
            android.widget.Toast.makeText(applicationContext, e.message, android.widget.Toast.LENGTH_LONG).show()
        }
    }
    
    private val takeImageResult = registerForActivityResult(TakePictureWithUriReturnContract()) { (isSuccess, imageUri) ->
        val myWebView: android.webkit.WebView = findViewById(R.id.webview_webview)
        if (isSuccess) {
            val imageStream: InputStream? = contentResolver.openInputStream(imageUri)
            val selectedImage = BitmapFactory.decodeStream(imageStream)
            val scaledImage = scaleDown(selectedImage, 800F, true)
            val baos = ByteArrayOutputStream()
            scaledImage?.compress(Bitmap.CompressFormat.JPEG, 100, baos)
            val byteArray: ByteArray = baos.toByteArray()
            val dataURL: String = Base64.encodeToString(byteArray, Base64.DEFAULT)
            myWebView.loadUrl( "JavaScript:fnWebAppReceiveImage('" + dataURL + "')" )
        }
        else {
            android.widget.Toast.makeText(applicationContext, "Image capture failed", android.widget.Toast.LENGTH_LONG).show()
        }
    }
    
    private inner class TakePictureWithUriReturnContract : ActivityResultContract<Uri, Pair<Boolean, Uri>>() {
        private lateinit var imageUri: Uri
        @CallSuper
        override fun createIntent(context: Context, input: Uri): Intent {
            imageUri = input
            return Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, input)
        }
        override fun getSynchronousResult(
            context: Context,
            input: Uri
        ): SynchronousResult<Pair<Boolean, Uri>>? = null
        @Suppress("AutoBoxing")
        override fun parseResult(resultCode: Int, intent: Intent?): Pair<Boolean, Uri> {
            return (resultCode == Activity.RESULT_OK) to imageUri
        }
    }

    private fun getTmpFileUri(): Uri? {
        val mediaStorageDir = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_TAG)
        if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
            throw Exception("Failed to create directory to store media temp file")
        }
        return FileProvider.getUriForFile(applicationContext, getApplicationContext().getPackageName() + ".provider", File(mediaStorageDir.path + File.separator + "photo.jpg"))
    }
    
    fun scaleDown(realImage: Bitmap, maxImageSize: Float, filter: Boolean): Bitmap? {
        val ratio = Math.min(maxImageSize / realImage.width, maxImageSize / realImage.height)
        val width = Math.round(ratio * realImage.width)
        val height = Math.round(ratio * realImage.height)
        return Bitmap.createScaledBitmap(realImage, width, height, filter)
    }
}

为了解决问题,这里是相关的 JavaScript 代码 - Activity 通过 myWebView.loadUrl(storedurl) 语句加载。

这是调用 Android 代码的 JavaScript 代码:

if (window.Android) {
    Android.image_capture();
}

拍完照片并使用 Android 代码调整大小后,它会将 Base64 发送回 JavaScript,其中:

myWebView.loadUrl("JavaScript:fnWebAppReceiveImage('" + dataURL + "')")

请注意您必须指定函数参数是多么奇怪。可能有更好的方法,但这段代码有效。如果有任何关于如何比这更容易指定函数参数的建议,请告诉我。

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.MyApp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        ...
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
    </application>
</manifest>

还有 provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path name="external_files" path="." />
</paths>

希望这对某人有所帮助 - 我花了好几天的时间才弄明白这个问题!