当前位置:网站首页>Compose implements WebView file selection
Compose implements WebView file selection
2022-07-21 04:17:00 【LiePy】
Recently in use compose Restructure the company's main APP, because compose Some unique design concepts of , There are also many problems in the development , Most of them can't even find relevant information on the Internet , I have to consult some obscure official documents by myself , Groping for solutions , And write it down , If necessary, you can provide reference .
It was realized before webView File selection is all done with Activity.startActivityForResult and onActivityResult Callback , But these two methods have security problems , Now the official is ready to abandon , Not recommended , Recommended registerForActivityResult and ActivityResultLauncher.lauch() Method to implement
One 、compose Use in webView
This part is not the focus of this article , I will not introduce you , You can refer to other articles on the Internet , for example :Jetpack Compose - WebView Usage method , Or look directly at wanAndroid The bosses compose edition wanAndroid Source code , Article address :Compose+MVI+Navigation Realization wanAndroid client , The structure is very clear
Two 、 To configure webSettings
Be careful to turn on javaScriptEnabled
@SuppressLint("SetJavaScriptEnabled")
private fun setWebSettings() {
val webSettings = webView.settings
// If you want to visit the page with Javascript Interaction , be webview Support... Must be set up Javascript
webSettings.javaScriptEnabled = true
// Set up the adaptive screen , Both of them work together
webSettings.useWideViewPort = true // Adjust the picture to fit webview Size
webSettings.loadWithOverviewMode = true // Zoom to the size of the screen
// Zoom operation
webSettings.setSupportZoom(true) // Support zoom , The default is true. It's the premise of the following .
webSettings.builtInZoomControls = true // Set the built-in zoom control . if false, Then WebView Not scalable
webSettings.displayZoomControls = false // Hide native zoom controls
webSettings.domStorageEnabled = true // Turn on DOM storage API function
// Other details
webSettings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK // close webview Medium cache
webSettings.allowFileAccess = true // Setting up access to files
webSettings.javaScriptCanOpenWindowsAutomatically = true // Supported by JS Open a new window
webSettings.loadsImagesAutomatically = true // Support automatic loading of pictures
webSettings.defaultTextEncodingName = "UTF-8"// Set the encoding format
}
3、 ... and 、 To configure WebViewChromeClient
Be careful : rewrite onShowFileChooser() Method , The method in Android5.0 There were two old versions before , But my project minSDK > 23 So just rewrite this version
private var uploadMessageAboveL: ValueCallback<Array<Uri>>? = null
inner class ProgressWebViewChromeClient : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
progressBar.progress = newProgress
}
override fun onReceivedTitle(view: WebView?, title: String?) {
super.onReceivedTitle(view, title)
}
override fun onShowFileChooser(
webView: WebView?,
filePathCallback: ValueCallback<Array<Uri>>?,
fileChooserParams: FileChooserParams?
): Boolean {
uploadMessageAboveL = filePathCallback
MyApp.imageResultLauncher.launch("image/*") return true } }
Four 、 register ResultLauncher
I was in Application Create and hold , stay Activity Of onCreate Register in
Due to the performance of frame structure and other reasons ,compose There is only one recommendation Activity, In my project, I need to integrate wechat login , So there's only one WxEntryActivity As the master Activity
@HiltAndroidApp
class MyApp: Application() {
companion object {
@SuppressLint("StaticFieldLeak")
lateinit var CONTEXT: Context
// establish ActivityResultLauncher, Used to receive onActivityResult The callback information of
lateinit var imageResultLauncher: ActivityResultLauncher<String>
// take ActivityResultLauncher The callback information of is passed to MutableLiveData, And in web The component listens for this LiveData
val imageResult: MutableLiveData<List<Uri>> = MutableLiveData()
}
override fun onCreate() {
super.onCreate()
CONTEXT = this
}
}
@AndroidEntryPoint
class WXEntryActivity : ComponentActivity() {
companion object {
const val TAG = "WXEntryActivity"
// Because this is the only one Activity, So it can be regarded as the overall situation lifeCycleOwner
lateinit var instant: WXEntryActivity
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
...
}
instant = this
// Register the picture selector
imageResultLauncher = registerForActivityResult(ActivityResultContracts.GetMultipleContents()) {
// Got pictures , Pass to LiveData
LogUtils.i("WXEntryActivity", "resultLauncher: $it")
imageResult.value = it
}
}
}
5、 ... and 、 establish result Of LiveData perhaps flow To set up ( send out ) And observation ( Accept ) data
You can see in the code of the previous step , I'm also in Application Create and hold imageResult This LiveData
Then update the data in the registered picture selector result callback
Last in webViewCtrl Monitor data changes in , And call uploadMessageAboveL Of onReceiveValue Callback . among uploadMessageAboveL See Step 3 for what is unclear , stay onShowFileChooser Lieutenant general filePathCallBack Quote to it
private fun initObserver() {
LogUtils.d("WebViewCtrl", "initObserver")
MyApp.imageResult.observe(WXEntryActivity.instant){
LogUtils.d("WebViewCtrl", "observe: $it")
uploadMessageAboveL?.onReceiveValue(it.toTypedArray())
}
}
边栏推荐
- Shell循环语句详解--while、until循环
- Understanding and use of unity2d custom scriptable tiles (II) -- understand the methods of the tilebase class (mainly gettiledata method) in detail by understanding the tile class
- Mysql-cve-2012-2122 vulnerability & redis vulnerability
- Jenkins sets the language to Chinese
- Model thesis of radio, film and television program production
- 栈模拟队列
- unity 生命游戏简单实现
- Yolo target detection identification box does not display text labels (solved)
- BeanUtils.copyProperties()和JSONObject.parseObject()是什么拷贝类型(浅拷贝或者深拷贝)
- 剑指offer专项突击版第4天
猜你喜欢
Building space temperature distribution prediction model and temperature curve drawing graduation thesis
Don't know how to learn MySQL? It's enough to finish the 50 questions of Niuke! (Part III)
pycharm 突然无法连接远程服务器
什么是FTP
One bite of Stream(5)
From buying servers to building personal blog websites | detailed process of graphics and text (Tencent cloud | pagoda panel | WordPress | argon)
McCabe度量方法计算程序复杂度
STM32学习(2)GPIO
The new version of WordPress 6.0.1 has been released, and it is recommended to update it all.
不知道 MySQL 咋学?刷完牛客这 50 道题就够了!(第三篇)
随机推荐
Understanding and using unity2d custom scriptable tiles (I) -- understanding the tilebase class
See "cocos2dx-3.0 as I understand it" in combination with the source code - Overview
Application of safertos in medical devices
STM32 learning (1) basic introduction
WordPress 6.0.1 新版已经发布,建议全部更新。
Pycharm suddenly cannot connect to the remote server
不知道 MySQL 咋学?刷完牛客这 50 道题就够了!(第四篇)
UGUI——CanvasUpdateRegistry
不知道 MySQL 咋学?刷完牛客这 50 道题就够了!(第五篇)
Unity realizes character movement and camera tracking
Unity2D 自定义Scriptable Tiles的理解与使用(二)——通过了解Tile类来对TileBase类的方法(主要是GetTileData方法)进行详细理解
不知道 MySQL 咋学?刷完牛客这 50 道题就够了!(第三篇)
Pytoch realizes handwritten digit recognition | MNIST data set (CNN convolutional neural network)
UGUI——RectMask2D
Optimizing graphics rendering in Unity games
二、mysql进程之间关系、配置文件、文件socket、网络socket、mysql密码破解
关于毕业前后的道路
Constructor, static method, abstract method, default method in interface
聪明人的游戏提高篇:第三章第二课:k个数乘(cheng)
[unity script optimization] unity magic methods