Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 WebView 데이터베이스를 활성화하는 방법 완벽 가이드

이 튜토리얼에서는 안드로이드 앱에서 WebView의 데이터베이스 기능을 활성화하여 특정 URL을 로드하는 방법을 단계별로 알아봅니다. WebView 데이터베이스를 활성화하면 웹 페이지가 localStorage나 IndexedDB 같은 클라이언트 측 저장소를 사용할 수 있어, 오프라인 데이터 저장이나 웹 앱 동작에 필수적입니다.

1단계: 새 프로젝트 생성하기

Android Studio를 실행하고 File → New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.

2단계: 레이아웃 파일 작성하기

다음 코드를 res/layout/activity_main.xml 파일에 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
   xmlns:app = "https://schemas.android.com/apk/res-auto"
   xmlns:tools = "https://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <WebView
      android:id = "@+id/web_view"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>

위 코드에서는 tutorialspoint.com 웹사이트를 화면에 표시하기 위한 WebView를 배치했습니다. LinearLayout 안에 WebView가 화면 전체를 채우도록 설정되어 있습니다.

3단계: MainActivity 구현하기

다음 코드를 src/MainActivity.java 파일에 추가합니다.

package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading Data...");
        progressDialog.setCancelable(false);
        WebView web_view = findViewById(R.id.web_view);
        web_view.requestFocus();
        web_view.getSettings().setLightTouchEnabled(true);
        web_view.getSettings().setDatabaseEnabled(true);
        web_view.loadUrl("https://www.tutorialspoint.com/");
        web_view.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress < 100) {
                    progressDialog.show();
                }
                if (progress == 100) {
                    progressDialog.dismiss();
                }
            }
        });
    }
}

주요 코드 설명

  • setDatabaseEnabled(true): 이 메서드가 핵심입니다. WebView의 DOM 저장소 데이터베이스 기능을 활성화하여 웹 페이지가 데이터를 저장할 수 있게 합니다.
  • ProgressDialog: 웹페이지 로딩 중에 진행 상태를 사용자에게 알려주는 다이얼로그입니다.
  • onProgressChanged(): WebChromeClient의 콜백 메서드로, 로딩 진행률에 따라 다이얼로그를 표시하거나 숨깁니다. 진행률이 100%가 되면 다이얼로그가 자동으로 닫힙니다.
  • loadUrl(): 지정된 URL을 WebView에서 불러옵니다.

4단계: 매니페스트 설정하기

인터넷 접근 권한이 필요하므로, 다음 코드를 AndroidManifest.xml 파일에 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
    package = "com.example.myapplication">
    <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:theme = "@style/AppTheme">
        <activity android:name = ".MainActivity">
            <intent-filter>
                <action android:name = "android.intent.action.MAIN" />
                <category android:name = "android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

<uses-permission android:name="android.permission.INTERNET"/> 태그를 반드시 선언해야 합니다. 이 권한이 없으면 WebView가 외부 웹사이트에 접속할 수 없습니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후, 툴바에서 Run(실행) 아이콘을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면, 모바일 기기에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 WebView 데이터베이스를 활성화하는 방법 완벽 가이드

마무리

이렇게 하면 안드로이드 WebView에서 데이터베이스 기능이 정상적으로 활성화됩니다. 참고로 최신 안드로이드 개발 환경에서는 ProgressDialog가 deprecated되었으므로, 실제 프로젝트에서는 ProgressBar나 커스텀 로딩 UI를 사용하는 것이 좋습니다. 또한 Android 9(API 28) 이상에서는 평문 HTTP 통신이 기본적으로 차단되므로, HTTPS URL을 사용하는 것이 권장됩니다.