Created
October 19, 2023 08:28
-
-
Save kvii/07ab28d72c3624068824ed837ed425b4 to your computer and use it in GitHub Desktop.
webview 支持 h5 扫码 demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:tools="http://schemas.android.com/tools"> | |
<uses-permission android:name="android.permission.INTERNET" /> | |
<!-- 需要添加以下权限 --> | |
<uses-feature android:name="android.hardware.camera" /> | |
<uses-feature android:name="android.hardware.camera.autofocus" /> | |
<uses-permission android:name="android.permission.CAMERA" /> | |
<uses-permission android:name="android.permission.RECORD_AUDIO" /> | |
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> | |
<!-- ... --> | |
</manifest> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : ComponentActivity() { | |
// 伴生类 | |
companion object { | |
const val CAMERA_OK = 1; | |
} | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
// jetpack compose 写的,webview 的 api 啥的都一样的。 | |
setContent { | |
AndroidView(modifier = Modifier.fillMaxSize(), factory = { ctx -> | |
WebView(ctx).apply { | |
webViewClient = object : WebViewClient() { | |
override fun onReceivedSslError( | |
view: WebView?, | |
handler: SslErrorHandler?, | |
error: SslError? | |
) { | |
handler?.proceed() // 忽略 ssl 错误 | |
} | |
} | |
webChromeClient = object : WebChromeClient() { | |
override fun onJsAlert( | |
view: WebView?, | |
url: String?, | |
message: String?, | |
result: JsResult? | |
): Boolean { | |
result?.confirm() // 不加的话第一次同意权限的时候会出问题 | |
return true; | |
} | |
override fun onPermissionRequest(request: PermissionRequest?) { | |
// 动态申请权限 | |
ActivityCompat.requestPermissions( | |
this@MainActivity, | |
arrayOf( | |
android.Manifest.permission.CAMERA, | |
android.Manifest.permission.WRITE_EXTERNAL_STORAGE | |
), | |
CAMERA_OK | |
) | |
// 允许权限 | |
request?.run { | |
grant(resources) | |
origin | |
} | |
} | |
} | |
settings.apply { | |
javaScriptEnabled = true // 支持 js 交互 | |
domStorageEnabled = true // 允许 local storage | |
} | |
loadUrl("页面的 url") | |
} | |
}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment