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

안드로이드 WebView에서 앱 캐시(App Cache) 활성화하는 방법 – 단계별 구현 가이드

이 예제는 안드로이드(Android)에서 WebView의 앱 캐시를 활성화하는 방법을 단계별로 보여줍니다. 앱 캐시를 사용하면 한 번 로드한 웹 콘텐츠를 기기에 저장해 두었다가 네트워크 상태가 좋지 않을 때에도 더 빠르게 페이지를 불러올 수 있습니다.

1단계: 새 프로젝트 생성

Android Studio에서 새 프로젝트를 만듭니다. 메뉴에서 File → New Project로 이동한 후, 프로젝트 생성에 필요한 모든 세부 정보(프로젝트 이름, 패키지명, 최소 SDK 버전 등)를 입력하여 새 프로젝트를 생성합니다.

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을 구성했습니다.

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.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
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().setJavaScriptEnabled(true);
        web_view.getSettings().setGeolocationEnabled(true);
        web_view.setSoundEffectsEnabled(true);
        web_view.getSettings().setAppCacheEnabled(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();
                }
            }
        });
    }
}

위 코드의 핵심은 다음과 같습니다.

  • setAppCacheEnabled(true): WebView의 앱 캐시 기능을 활성화하는 핵심 메서드입니다.
  • setJavaScriptEnabled(true): 대부분의 웹사이트가 정상적으로 동작하도록 자바스크립트를 허용합니다.
  • WebChromeClient의 onProgressChanged(): 페이지 로딩 진행률에 따라 ProgressDialog를 표시하거나 숨겨 사용자에게 로딩 상태를 알려줍니다.

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>

인터넷에 연결된 웹페이지를 로드해야 하므로 android.permission.INTERNET 권한 선언이 반드시 필요합니다. 이 권한이 없으면 WebView가 아무것도 표시하지 못합니다.

앱 실행 및 결과 확인

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

안드로이드 WebView에서 앱 캐시(App Cache) 활성화하는 방법 – 단계별 구현 가이드

참고 사항

setAppCacheEnabled() 메서드는 오래된 HTML5 Application Cache(API) 기반으로 동작하며, 최신 안드로이드 버전(API 33 이상)에서는 공식적으로 지원 중단(deprecated)되었습니다. 신규 프로젝트에서는 Service Worker 기반의 PWA 캐싱이나 CacheMode(LOAD_CACHE_ELSE_NETWORK 등) 설정을 함께 검토하는 것이 좋습니다.