Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách tạo WebView trong ứng dụng Android

Giới thiệu

Hướng dẫn này trình bày cách tạo WebView để hiển thị trang web bên trong ứng dụng Android, bao gồm bật JavaScript và xử lý nút Back.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    xmlns:tools="https://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">
    </WebView>
</RelativeLayout>

Bước 3: Viết logic xử lý (src/MainActivity.java)

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private WebView webView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        webView = findViewById(R.id.webView);
        
        // Quan trọng: Set WebViewClient để link mở trong app, không mở trình duyệt ngoài
        webView.setWebViewClient(new WebViewClient());
        
        // Tải URL
        webView.loadUrl("https://www.google.com");
        
        // Bật JavaScript (mặc định là tắt)
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        
        // Các thiết lập hữu ích khác
        webSettings.setDomStorageEnabled(true);        // LocalStorage
        webSettings.setLoadWithOverviewMode(true);     // Zoom to fit
        webSettings.setUseWideViewPort(true);          // Wide viewport
        webSettings.setBuiltInZoomControls(true);      // Zoom controls
        webSettings.setDisplayZoomControls(false);     // Ẩn nút zoom
        webSettings.setSupportZoom(true);              // Hỗ trợ zoom
    }
    
    // Xử lý nút Back vật lý: quay lại trang web trước nếu có
    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

Bước 4: Cấu hình Manifest (androidManifest.xml) - Cần quyền Internet

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <!-- Quyền Internet BẮT BUỘC -->
    <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>

Lưu ý quan trọng về bảo mật

  • Cleartext traffic: Từ Android 9 (API 28), HTTP bị chặn mặc định. Cần cấu hình network_security_config.xml hoặc dùng HTTPS
  • JavaScript Interface: Nếu dùng addJavascriptInterface(), chỉ annotate @JavascriptInterface cho method public, và KHÔNG dùng cho web không tin cậy (XSS risk)
  • Mixed Content: HTTPS page load HTTP resource sẽ bị chặn

Cấu hình Network Security (res/xml/network_security_config.xml)

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain> <!-- localhost emulator -->
        <domain includeSubdomains="true">your-dev-server.com</domain>
    </domain-config>
</network-security-config>

Thêm vào Manifest: android:networkSecurityConfig="@xml/network_security_config"

Chạy ứng dụng

Kết nối thiết bị Android, nhấn Run trong Android Studio. WebView sẽ tải Google.com, cho phép điều hướng, zoom, và nút Back hoạt động đúng.

Cách tạo WebView trong ứng dụng Android

Cách tạo WebView trong ứng dụng Android