Android intent在回调中总是有null(使用registerForActivityResult)



我正在使用这个代码,我错过了一些东西,因为几乎一切都在工作,但是当回调响应时,我在数据中得到null:

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没有文档返回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代码-活动是通过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>

希望这对某人有所帮助-我花了几天的研究才弄清楚这一点!

相关内容

  • 没有找到相关文章

最新更新