먼저 WebView의 만드는 방법을 알아 봤다.
근데 WebView를 만든뒤에 확인해 보면 WebView에서 새로운 Url 접속이 일어 날면
새로운 창이 뜨는걸 볼 수 있다. 이는 기본적으로 WebView에서 새로운 Url 접속시
시스템에서 새로운 창에다가 로딩하도록 시키는 것인데, 이것이 한두번씩 많아지면
메모리 관리상에도 별로 도움이 안된다. 그럼 어찌해야 될까..
그래서 있는 것이 WebViewClient 와 WebChromeClient 이다.
이번 장에는 webViewClient class 에 대해서 알아보자.
이제 WebChromeClient를 알아 보면
WebChromeClient는 현제 페이지에서 일어나는 알람등을 알려 주기 위한 콜백 인터페이스라고 설명되어 있습니다.
사용하는 방법은 마찬가지입니다.
private class WebChromeClass extends WebChromeClient{
~~~~~~~~~~~~ 내용 ~~~~~~~~~~~~~~~~~~~~~~
}
과 내부에서 new로 생성해도 됩니다.
WebView.setWebChromeClient(new WebChromeClient(){
~~~~~~~~~~~ 내용 ~~~~~~~~~~~~~~~~~~~~~~
}
이렇게 하시면 됩니다.
WebChromeClient Class 함수들에 대해서 알아보자.
1. onProgressChanged()
페이지를 로딩하는 현재 진행 상황을 전해줍니다.
현재 페이지 로딩 진행 상황, 0과 100 사이의 정수로 표현.(0% ~ 100%)
@Override
public void onProgressChanged(WebView view, int newProgress) {
Log.i("WebView", "Progress: " + String.valueOf(newProgress));
super.onProgressChanged(view, newProgress);
}
(예제) onProgressChanged()
일단 Progress Bar를 하나 만드신 후에
private ProgressBar web_progress;
web_progress = (ProgressBar)findViewById(R.id.progress);
web_progress.setVisibility(View.GONE); //화면에서 숨김니다
@Override
public void onProgressChanged(WebView view, int newProgress){
web_progress.setVisibility(View.VISIBLE); // 화면에 보이기
//진행상황이 100%이상이면
if(newProgress > 100){
web_progress.setVisibility(View.GONE); //화면서 감추기
}
}
이제 화면에서 Progress Bar가 나왔다가 사라지는걸 볼 수 있을껍니다.^^
2. onReceivedIcon()
현재 페이지에 새로운 favicon이 있다고 알립니다.
icon 현재 페이지의 favicon이 들어있는 비트맵
favicon이란: 일반적으로 웹 브라우저의 URL이 표시되기 전에 특정 웹사이트와 관련된 16 × 16 픽셀 아이콘
@Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
}
3. onReceivedTitle()
문서 제목에 변경이 있다고 알립니다.
title 문서의 새로운 타이틀이 들어있는 문자열
/* 아래처럼 title 태그 사이의 값을 가져옵니다.
<title> LG텔레콤 전자결제 서비스 </title>
*/
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
4. getDefaultVideoPoster()
문서 제목에 변경이 있다고 알립니다.
title 문서의 새로운 타이틀이 들어있는 문자열
/* 아래처럼 title 태그 사이의 값을 가져옵니다.
<title> LG텔레콤 전자결제 서비스 </title>
*/
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
5. onJsAlert()
자바 스크립트 경고 대화 상자를 디스플레이한다고 클라이언트에게 알려줍니다.
클라이언트가 true를 반환할 경우, WebView는 클라이언트가 대화 상자를 처리할 수 있다고 여깁니다.
클라이언트가 false를 반환할 경우, WebView는 실행을 계속합니다.
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
return super.onJsAlert(view, url, message, result);
}
(예제) onJsAlert() - AlertDialog 생성
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result)
{
final JsResult finalRes = result;
//AlertDialog 생성
new AlertDialog.Builder(view.getContext())
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finalRes.confirm();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
6. onJsBeforeUnload()
현재 페이지에서 나와 탐색을 확정하는 대화 상자를 디스플레이한다고 클라이언트에게
알려줍니다. 이것은 자바 스크립트 이벤트 onbeforeunload()의 결과입니다. 클라이언트가
true를 반환하는 경우, WebView는 클라이언트가 대화 상자를 처리하고 적절한 JsResult
메쏘드를 호출할 것이라고 여깁니다. 클라이언트가 false를 반환하는 경우, true의 기본값은
현재 페이지에서 나와 탐색하기를 수락하기 위한 자바 스크립트를 반환하게 될 것입니다.
기본 동작은 false를 반환하는 것입니다. JsResult를 true로 설정한 것은 현재 페이지에서 나와
탐색할 것이고 false로 설정한 것은 탐색을 취소할 것입니다.
클라이언트가 false를 반환할 경우, WebView는 실행을 계속합니다.
@Override
public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
return super.onJsBeforeUnload(view, url, message, result);
}
7. onJsConfirm()
사용자에게 확인 대화 상자를 디스플레이한다고 클라이언트에게 알려줍니다. 클라이언트가
true를 반환하는 경우, WebView는 클라이언트가 확인 대화 상자를 처리하고 적절한
JsResult 메쏘드를 호출할 수 있다고 여깁니다. 클라이언트가 false를 반환하는 경우 false의
기본값은 자바 스크립트로 반환될 것 입니다. 기본 동작은 false를 반환하는 것입니다.
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
return super.onJsConfirm(view, url, message, result);
}
(예제) onJsConfirm() - confirm 창 띄우는 예제.
@Override
public boolean onJsConfirm(WebView view, String url, String message, final android.webkit.JsResult result){
new AlertDialog.Builder(view.getContext())
.setTitle("좋은데...")
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
})
.create()
.show();
return true;
};
8. onJsPrompt()
사용자에게 프롬프트 대화 상자를 디스플레이한다고 클라이언트에게 알려줍니다.
클라이언트가 true를 반환하는 경우, WebView는 클라이언트가 확인 대화 상자를 처리하고
적절한 JsResult 메쏘드를 호출할 수 있다고 여깁니다. 클라이언트가 false를 반환하는 경우
false의 기본값은 자바 스크립트로 반환될 것 입니다. 기본 동작은 false를 반환하는 것입니다.
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
return super.onJsPrompt(view, url, message, defaultValue, result);
}
9. onJsTimeout()
자바 스크립트 실행 제한 시간을 초과했다고 클라이언트에게 알려줍니다. 그리고
클라이언트가 실행을 중단할지 여부를 결정할 수 있습니다. 클라이언트가 true를 반환하는
경우, 자바 스크립트가 중단됩니다. 클라이언트가 false를 반환하는 경우, 계속 실행됩니다.
참고로 지속적인 실행 상태에서는 제한 시간 카운터가 재설정되고 스크립트가 다음 체크
포인트에서 완료되지 않을 경우 계속 콜백되어질 것집니다.
@Override
public boolean onJsTimeout() {
return super.onJsTimeout();
}
10. openFileChooser()
웹페이지상에서 파일 첨부를 해야 할 경우가 있다. 이경우에 사용하는 메서드 이다.
// For Android < 3.0
public void openFileChooser( ValueCallback uploadMsg ){
openFileChooser( uploadMsg, "" );
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg) {
uploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
//i.setType("*/*");
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 4.1+
public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
openFileChooser( uploadMsg, "" );
}
여기서 중요한점은 @Override 를 쓰면 오류난다는 것이다.
왜냐하면 openFileChooser 메소드는 프레임웍에서 @hidden 처리되어있기때문에 sdk 에서 보이지 않기 때문이다.
하여튼 인앱브라우저에서 파일첨부를 하려고하면 저 메소드가 자동으로 호출되게 된다.
기타 함수들....
@Override
public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota, QuotaUpdater quotaUpdater) {
super.onReachedMaxAppCacheSize(spaceNeeded, totalUsedQuota, quotaUpdater);
}
---------------------------------------------------------------------
@Override
public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
super.onReceivedTouchIconUrl(view, url, precomposed);
}
---------------------------------------------------------------------
@Override
public void onRequestFocus(WebView view) {
super.onRequestFocus(view);
}
---------------------------------------------------------------------
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
}
---------------------------------------------------------------------
@Override
public Bitmap getDefaultVideoPoster() {
return super.getDefaultVideoPoster();
}
---------------------------------------------------------------------
@Override
public View getVideoLoadingProgressView() {
return super.getVideoLoadingProgressView();
}
---------------------------------------------------------------------
@Override
public void getVisitedHistory(ValueCallback callback) {
super.getVisitedHistory(callback);
}
---------------------------------------------------------------------
@Override
public void onCloseWindow(WebView window) {
super.onCloseWindow(window);
}
---------------------------------------------------------------------
@Override
public void onConsoleMessage(String message, int lineNumber, String sourceID) {
super.onConsoleMessage(message, lineNumber, sourceID);
}
---------------------------------------------------------------------
@Override
public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg) {
return super.onCreateWindow(view, dialog, userGesture, resultMsg);
}
---------------------------------------------------------------------
@Override
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
long totalUsedQuota, QuotaUpdater quotaUpdater) {
super.onExceededDatabaseQuota(url, databaseIdentifier, currentQuota,
estimatedSize, totalUsedQuota, quotaUpdater);
}
---------------------------------------------------------------------
@Override
public void onGeolocationPermissionsHidePrompt() {
super.onGeolocationPermissionsHidePrompt();
}
---------------------------------------------------------------------
@Override
public void onGeolocationPermissionsShowPrompt(String origin,Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
}
---------------------------------------------------------------------
@Override
public void onHideCustomView() {
super.onHideCustomView();
}