3

I need to implement the select file option in my webviewActivity and all the tutorials I found have only the example with the startActivityResult, but it is currently deprecated and so I would like some help on how to transform this code to the new templates of a register as in the documentation: https://developer.android.com/training/basics/intents/result.

WebviewActivity.kt

class WebviewActivity: AppCompatActivity() {
val REQUEST_SELECT_FILE = 1
val FILE_CHOOSER_RESULT = 2
var uploadMessage: ValueCallback<Array<Uri>>? = null
var uploaded: ValueCallback<Uri>? = null

private fun launchWebview(url: String): WebView =
    webview_id.apply{
        loadUrl(url)
        webViewClient : object = WebViewClient(){
            //...//
        }

        webChromeClient : object = WebChromeClient(){
            override fun onShowFileChooser(
                webView: WebView?,
                filePathCallback: ValueCallback<Array<Uri>>?,
                fileChooserParams: WebChromeClient.FileChooserParams
            ): Boolean{
                if (uploadMessage != null){
                    uploadMessage!!.onReceiveValue(null)
                    uploadMessage = null
                }

                uploadMessage = filePathCallback
                val intent = fileChooserParams.createIntent()

                startActivityForResult(intent, REQUEST_SELECT_FILE)

                return true
            }
        }
    }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == REQUEST_SELECT_FILE){
        uploadMessage!!.onReceiveValue(
            WebChromeClient.FileChooserParams.parseResult(
                resultCode, data
            )
        )
        uploadMessage = null
    } else if (requestCode == FILE_CHOOSER_RESULT){
        val result = if (data == null || resultCode != RESULT_OK) null else data.data
        uploaded!!.onReceiveValue(result)
        uploaded = null
    }
    super.onActivityResult(requestCode, resultCode, data)
}
}

I used this link to make the code above: Android File Chooser not calling from Android Webview

1 Answers1

1

You have to do sth. like that:

private fun createFile() {
  getResult.launch("chartName.pdf")
}

private val getResult = registerForActivityResult(
  CreateSpecificTypeDocument("application/pdf")
) { uri ->
  if(uri != null){
    contentResolver.openFileDescriptor(uri, "w")?.use {
      FileOutputStream(it.fileDescriptor).use { fileOutputStream ->
        //DO sth. with file
      }
    }
  }
}

with:

class CreateSpecificTypeDocument(private val type: String) :
  ActivityResultContracts.CreateDocument() {
  override fun createIntent(context: Context, input: String): Intent {
    return super.createIntent(context, input).setType(type)
  }
}