[안드로이드] Webview 구현

변준영·2022년 12월 7일
0

Webview란?

  • WebView는 웹페이지를 Activity의 일부로 표시
  • 탐색 컨트롤이나 주소 표시줄 등 완전히 개발된 웹브라우저의 기능은 전혀 포함되어 있지 않음

Webview 개발하기

1. XML

  • Webview를 이해하기 위해 activity_main.xml에는 Webview만 추가
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </LinearLayout>

2. AndroidManifest.xml

  • 작업을 수행하려면 앱이 인터넷에 액세스할 수 있어야 함

  • AndroidManifest.xml에 다음을 추가하여 인터넷 액세스 권한 요청

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    	...
     	<uses-permission android:name="android.permission.INTERNET" />
    	...
    </manifest>
  • 인터넷에서 htts의 보안이 아닌 일반 http사이트를 접근하기 위하여 다음 추가 [2]

    <application
    	...
    	android:usesCleartextTraffic="true"
    	...
    </application>       

3. java

import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private WebView myWebView;
    private String myUrl = "http://www.naver.com";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // findViewById
        myWebView = (WebView) findViewById(R.id.webView);

        // 웹 URL 설정
        myWebView.loadUrl(myUrl);

        // 이용하고자 하는 web이 javascript를 사용할 경우 다음과 같이 설정
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // 어플 내 웹 띄우기
        myWebView.setWebViewClient(new WebViewClient());
    }

    // 뒤로가기 설정
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 뒤로가기 버튼을 눌렀을 때 이전 기록이 있으면 이전 페이지 이동
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
            myWebView.goBack();
            return true;
        }
        // 이전페이지 기록이 없을 시 기본 기능 수행 (앱 종료 등)
        return super.onKeyDown(keyCode, event);
    }
}

4. 실행화면

  • 다음과 같이 웹페이지가 뜨는 것을 확인 할 수 있다.

<Debbug>[3]

  • 크롬을 사용하여 웹뷰 디버깅
  • 다음과 같이 디버깅 진행

1. USB 디버깅 활성화

설정 -개발자 옵션 - USB 디버깅 : 활성화	

2. onCreate()에 다음 코드 추가

// 디버깅 허용
myWebView.setWebContentsDebuggingEnabled(true); 

3. 앱 실행

4. chrome://inspect/#devices 접속하여 inspect 클릭

5. 디버깅

참고

[1] https://developer.android.com/guide/webapps/webview?hl=ko
[2] https://m.blog.naver.com/stk222/221906893206
[3] https://kotlinworld.com/363

코드 : https://github.com/jybyun9533/Android_Study/tree/master/WebView01

0개의 댓글