2. 웹뷰실습
페이지 정보
작성자 관리자 댓글 0건 조회 1,932회 작성일 22-01-14 21:26본문
1. 프로젝트를 생성한다.
프로젝트 명 : WebView
2. 권한 설정 : AndroidMenifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="kr.co.leelab.webview">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/Theme.View">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3. 레이아웃 수정 : activity_main.xml
레이아웃에 WebView를 추가한다. 웹뷰를 불러오는 동안 로딩바를 추가하기 위해 ProgressBar를 추가한다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
android:id="@+id/progress1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
4. 웹사이트 호출 : MainActivity.kt
loadUrl() 메소드를 사용하여 웹사이트를 호출한다.
package kr.co.leelab.webview
import android.app.Dialog
import android.content.DialogInterface
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Message
import android.provider.Settings
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import android.widget.ProgressBar
class MainActivity : AppCompatActivity() {
private lateinit var webView: WebView
private lateinit var mProgressBar: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView = findViewById(R.id.webView1)
mProgressBar = findViewById(R.id.progress1)
webView.apply {
webViewClient = WebViewClientClass()
// 팝업이나 파일 업로드 등 설정해주기 위해 webView.webChromeClient를 설정
//웹뷰에서 팝업창 호출하기 위해
webChromeClient = object: WebChromeClient() {
override fun onCreateWindow(
view: WebView?,
isDialog: Boolean,
isUserGesture: Boolean,
resultMsg: Message?
): Boolean {
val newWebView = WebView(this@MainActivity).apply {
webViewClient = WebViewClient()
settings.javaScriptEnabled = true
}
val dialog = Dialog(this@MainActivity).apply {
setContentView(newWebView)
window!!.attributes.width = ViewGroup.LayoutParams.MATCH_PARENT
window!!.attributes.height = ViewGroup.LayoutParams.MATCH_PARENT
show()
}
newWebView.webChromeClient = object: WebChromeClient() {
override fun onCloseWindow(window: WebView?) {
//super.onCloseWindow(window)
dialog.dismiss()
}
}
(resultMsg?.obj as WebView.WebViewTransport).webView = newWebView
resultMsg.sendToTarget()
return true
}
}
settings.javaScriptEnabled = true
settings.setSupportMultipleWindows(true) // 새창띄우기 허용여부
settings.javaScriptCanOpenWindowsAutomatically = true // 자바스크립트트 새창 띄우기
settings.loadWithOverviewMode = true // 메타테그 허용 여부
settings.useWideViewPort= true // 화면 사이즈 맞추기 허용 여부
settings.setSupportZoom(true) // 화면 줌 허용 여부
settings.builtInZoomControls = true // 화면 확대 축소 허용 여부
// Enable and setup web view cache
settings.cacheMode = WebSettings.LOAD_NO_CACHE // 브라우저 캐시 허용 여부
settings.domStorageEnabled = true // 로컬 저장소 허용 여부
settings.displayZoomControls = true
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
settings.safeBrowsingEnabled = true //api 26
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.mediaPlaybackRequiresUserGesture = false
}
settings.allowContentAccess = true
settings.setGeolocationEnabled(true)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
settings.allowUniversalAccessFromFileURLs = true
}
settings.allowFileAccess = true
//settings.loadsImagesAutomatically = true
fitsSystemWindows = true
}
val url = "https://www.leelab.co.kr"
webView.loadUrl(url)
}
//웹뷰에서 홈페이지를 띄웠을 때 새창이 아닌 기존창에서 실행이 되도록 아래 코드를 넣어준다.
inner class WebViewClientClass: WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return true
}
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
mProgressBar.visibility = ProgressBar.VISIBLE
webView.visibility = View.INVISIBLE
}
override fun onPageCommitVisible(view: WebView?, url: String?) {
super.onPageCommitVisible(view, url)
mProgressBar.visibility = ProgressBar.GONE
webView.visibility = View.VISIBLE
}
override fun onReceivedSslError(
view: WebView,
handler: SslErrorHandler,
error: SslError
) {
super.onReceivedSslError(view, handler, error)
var builder: android.app.AlertDialog.Builder = android.app.AlertDialog.Builder(this@MainActivity)
var message = "SSL Certificate error."
when (error.primaryError) {
SslError.SSL_UNTRUSTED -> message = "The certificate authority is not trusted."
SslError.SSL_EXPIRED -> message = "The certificate has expired."
SslError.SSL_IDMISMATCH -> message = "The certificate Hostname mismatch."
SslError.SSL_NOTYETVALID -> message = "The certificate is not yet valid."
}
message += " Do you want to continue anyway?"
builder.setTitle("SSL Certificate Error")
builder.setMessage(message)
builder.setPositiveButton("continue",
DialogInterface.OnClickListener { dialog, which -> handler.proceed() })
builder.setNegativeButton("cancel",
DialogInterface.OnClickListener { dialog, which -> handler.cancel() })
val dialog: android.app.AlertDialog?= builder.create()
dialog?.show()
}
}
}
댓글목록
등록된 댓글이 없습니다.