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

안드로이드 WebView 렌더링 우선순위(Render Priority) 설정 방법 – 단계별 완벽 가이드

개요

이 튜토리얼에서는 안드로이드(Android) 앱에서 WebView의 렌더링 우선순위(Render Priority)를 설정하는 방법을 단계별로 살펴봅니다. 렌더링 우선순위를 조정하면 WebView가 웹 콘텐츠를 그리는 처리 순서를 제어할 수 있어, 웹페이지 로딩 성능과 반응성을 개선하는 데 도움이 됩니다.

1단계 — 새 프로젝트 생성

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

2단계 — 레이아웃 파일(activity_main.xml) 작성

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 하나를 배치했습니다.

3단계 — MainActivity.java 작성

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.setSoundEffectsEnabled(true);
      web_view.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
      web_view.getSettings().setUseWideViewPort(true);

      // 핵심 부분: 렌더링 우선순위를 HIGH로 설정
      web_view.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);

      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();
            }
         }
      });
   }
}

여기서 핵심은 바로 setRenderPriority(WebSettings.RenderPriority.HIGH) 호출입니다. 이 메서드는 세 가지 값을 받을 수 있습니다.

  • HIGH — WebView 렌더링에 더 많은 CPU 리소스를 할당하여 렌더링 속도를 높입니다.
  • NORMAL — 기본값으로, 일반적인 균형 잡힌 우선순위를 사용합니다.
  • LOW — 렌더링 우선순위를 낮추어 다른 UI 작업에 리소스를 양보합니다.

또한 WebChromeClientonProgressChanged() 콜백을 활용해 페이지 로딩 진행률에 따라 ProgressDialog를 표시하거나 닫도록 구현했습니다.

참고: setRenderPriority()는 API 레벨 18부터 공식적으로 지원 중단(deprecated)되었으며, 현재는 시스템이 자동으로 렌더링 우선순위를 관리합니다. 따라서 최신 프로젝트에서는 이 설정이 큰 효과를 보지 못할 수 있지만, 레거시 코드 유지보수나 학습 목적이라면 여전히 유용하게 참고할 수 있습니다.

4단계 — AndroidManifest.xml 설정

웹 콘텐츠를 불러오려면 인터넷 권한이 필요합니다. 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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후, 툴바에서 Run 아이콘을 클릭하세요. 실행 옵션 목록에서 모바일 기기를 선택하면, 기기 화면에 아래와 같은 결과가 표시됩니다.

안드로이드 WebView 렌더링 우선순위(Render Priority) 설정 방법 – 단계별 완벽 가이드