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

안드로이드에서 캐시를 이용해 WebView를 로드하는 방법

이 글에서는 안드로이드(Android) 앱에서 캐시를 활용해 WebView를 로드하는 방법을 단계별로 살펴봅니다. 캐시 모드를 적절히 설정하면 네트워크 상태와 관계없이 저장된 데이터를 빠르게 불러올 수 있어, 오프라인 환경에서도 웹 콘텐츠를 원활하게 표시할 수 있습니다.

핵심 개념: WebView 캐시 모드

안드로이드의 WebSettings 클래스는 다음과 같은 캐시 모드를 제공합니다.

  • LOAD_DEFAULT — 기본 동작. 캐시 만료 여부에 따라 네트워크 또는 캐시 사용
  • LOAD_CACHE_ELSE_NETWORK — 캐시에 콘텐츠가 있으면 네트워크 상태와 무관하게 캐시 우선 사용
  • LOAD_NO_CACHE — 항상 네트워크에서만 콘텐츠 로드
  • LOAD_CACHE_ONLY — 네트워크를 사용하지 않고 캐시에서만 로드

이 예제에서는 LOAD_CACHE_ELSE_NETWORK 모드를 사용합니다.

구현 단계

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>

위 레이아웃에는 mylocation.org 사이트를 표시할 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.WebSettings;
import android.webkit.WebView;

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().setJavaScriptEnabled(true);
        web_view.getSettings().setGeolocationEnabled(true);
        web_view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        web_view.loadUrl("https://mylocation.org/");

        web_view.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress < 100) {
                    progressDialog.show();
                }
                if (progress == 100) {
                    progressDialog.dismiss();
                }
            }
        });
    }
}

위 코드의 핵심은 setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK) 호출입니다. 이 설정 덕분에 캐시된 콘텐츠가 있을 경우 네트워크보다 캐시를 먼저 사용하게 됩니다. 또한 JavaScript와 위치 정보(Geolocation)를 활성화했으며, WebChromeClient의 onProgressChanged() 콜백에서 로딩 진행률이 100% 미만일 때는 ProgressDialog를 표시하고, 100%에 도달하면 이를 닫도록 처리했습니다.

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>

WebView로 외부 웹 페이지를 로드하려면 android.permission.INTERNET 권한 선언이 반드시 필요합니다.

앱 실행 및 결과 확인

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

안드로이드에서 캐시를 이용해 WebView를 로드하는 방법