I have just a full screen WebView with a web-page where user can navigate. I need to make available uploading files in webview, for example attach files in gmail or send files in messanger. The problem is that now file attaching buttons just don't react, for example in Google Photos:
I need to work them exactly like in browser when it proposes the user to choose application for file uploading through implicit Intent. I suppose that I should use implicit Intent but don't know how to implement it in webview.
I enabled some necessary permissions and even more:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CAMERA"/>
Please tell me what decision is up-to-date and works for application with single webView. Unfortunately none of decisions here helped, may be because they are way too old: File Upload in WebView
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
if (savedInstanceState != null) {
// Restore the previous URL and history stack
binding.webView.restoreState(savedInstanceState);
}
val myWebViewClient = MyWebViewClient(this)
binding.webView.settings.javaScriptEnabled = true
val currentUrl = myWebViewClient.sharedPref.getString(URL, "https://www.google.ru")
Log.d(tag, "sharedPref value: ${myWebViewClient.sharedPref.getString(URL, "")}")
if (currentUrl != null) {
binding.webView.loadUrl(currentUrl)
}
binding.webView.webViewClient = myWebViewClient
}
override fun onBackPressed() {
binding.webView.apply {
if (canGoBack()) {
goBack()
} else {
onBackPressed()
}
}
}
}
MyWebViewClient class:
val tag = "CUSTOMTAG"
val SHARED_PREFS = "sharedPrefs"
val URL = "URL"
class MyWebViewClient(val context: Context) : WebViewClient() {
val sharedPref = context.getSharedPreferences(
SHARED_PREFS,
AppCompatActivity.MODE_PRIVATE
)
override fun shouldOverrideUrlLoading(view: WebView?, url: String): Boolean {
view?.let {
it.loadUrl(url)
}
return false
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
with(sharedPref.edit()) {
putString(URL, url)
apply()
}
if (url != null) {
sharedPref.getString(URL, "")?.let { Log.d(tag, "sharedPref: $it") }
}
}
}