Android WebView应用深度链接:实现特定URL在应用内打开而非浏览器

本教程详细阐述如何在基于WebView的Android应用中,通过配置AndroidManifest.xml的intent-filter,实现对特定URL的深度链接。用户点击包含应用域名的链接时,系统将直接启动应用并加载该URL,而非默认的Web浏览器,从而提升用户体验并确保内容在应用环境中呈现。

在Android开发中,许多应用程序选择使用WebView来承载其Web内容,这使得混合应用开发变得高效。然而,一个常见的需求是确保当用户点击一个与应用关联的特定URL(例如,通过消息应用分享的链接)时,该链接能够直接在原生Android应用中打开,而不是启动外部Web浏览器。这种机制被称为深度链接(Deep Linking)或应用链接(App Links)。

核心解决方案:配置 AndroidManifest.xml 实现深度链接

实现这一功能的关键在于在您的AndroidManifest.xml文件中正确声明一个intent-filter。这个过滤器会告知Android操作系统,您的应用程序能够处理特定模式的Web URL。

1. 修改 AndroidManifest.xml

在您希望处理这些URL的Activity的标签内部,添加以下intent-filter配置:

 
    
    
        
        
    

    
    
        
        
        
        
        
        
        
        
    

标签解释:

  • android:name="android.intent.action.VIEW": 声明此intent-filter用于响应用户尝试“查看”数据(通常是URL)的意图。
  • android:name="android.intent.category.DEFAULT": 允许此Activity接收不带特定类别的隐式Intent。这是响应通用Web链接所必需的。
  • android:name="android.intent.category.BROWSABLE": 允许Activity安全地被Web浏览器调用,以处理链接。没有此类别,浏览器将无法启动您的应用。
  • data 标签: 这是定义应用可以处理的URL模式的核心。
    • android:scheme: 指定URL的协议(例如 https 或 http)。
    • android:host: 指定URL的主机名(例如 tcg-wallet.ga)。
    • 您还可以使用 android:pathPrefix、android:path 或 android:pathPattern 来匹配更具体的URL路径,从而实现更精细的控制。
  • android:exported="true": 从Android 12 (API 31) 开始,如果您的Activity包含intent-filter且需要被外部组件(如系统或第三方应用)启动,必须明确设置此属性为true。

在Activity中处理传入的URL

一旦用户点击了符合上述intent-filter定义的URL,Android系统将启动或唤醒您的指定Activity。您需要在该Activity的onCreate()或onNewIntent()方法中获取并处理传入的URL数据。

示例代码:

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

// 导入 WebViewClient public class YourMainActivity extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 假设您的布局文件中有 WebView webView = findViewById(R.id.your_webview_id); // 替换为您的 WebView ID // 配置 WebView 设置,例如启用 JavaScript webView.getSettings().setJavaScriptEnabled(true); // 确保 WebView 在应用内加载链接,而不是打开外部浏览器 webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); handleIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); // 更新当前Activity的Intent handleIntent(intent); } private void handleIntent(Intent intent) { String action = intent.getAction(); Uri data = intent.getData(); if (Intent.ACTION_VIEW.equals(action) && data != null) { // 获取完整的URL String fullUrl = data.toString(); // 例如:https://tcg-wallet.ga/home?search=MP21-EN056&event=search // 您也可以通过 data.getQueryParameter("search") 获取特定参数 // 将URL加载到 WebView if (webView != null) { webView.loadUrl(fullUrl); } // 或者根据解析出的参数执行其他应用逻辑 // String searchParam = data.getQueryParameter("search"); // if (searchParam != null) { // // 执行搜索操作或跳转到应用内特定页面 // } } else { // 处理常规启动逻辑,例如加载默认主页 if (webView != null) { webView.loadUrl("https://tcg-wallet.ga/home"); // 您的默认主页 } } } }

说明:

  • getIntent().getData() 方法用于获取触发此Activity的URI。
  • onNewIntent() 方法用于处理当Activity已经在运行(例如,其启动模式为singleTop或singleTask)时,系统再次发送Intent的情况。
  • 获取到URL后,您可以选择直接将其加载到WebView中,或者解析URL中的查询参数(如search)来执行特定的应用内操作,从而实现更灵活的导航。
  • webView.setWebViewClient() 的设置是关键,它确保了在WebView内部点击的链接也会在WebView中加载,而不是再次启动外部浏览器。

从WebView分享链接的实现(上下文)

虽然上述深度链接配置解决了外部链接唤醒应用的问题,但原始问题中也涉及从WebView内部触发分享。这部分代码主要负责将WebView中的数据传递给Android原生分享接口,并不会直接影响深度链接的行为,而是为用户提供了分享链接的入口。

1. JavaScript 代码示例 (在 WebView 页面中):

在您的Web页面中,添加一个按钮和相应的JavaScript代码来调用Android原生分享接口。

const shareData = {
    title: '搜索价格',
    text: '搜索卡片通过: "' + document.getElementById('search').value + '"',
    url: document.URL // 当前页面的完整URL
};

const btn = document.getElementById('share-url');

if (typeof btn !== 'undefined' && btn !== null) { // 确保按钮存在
    btn.addEventListener('click', async () => {
        try {
            if (typeof (window.AndroidShareHandler) != 'undefined') {
                // 调用原生 Android 接口
                window.AndroidShareHandler.shareSearch(JSON.stringify(shareData));
            } else if (navigator.share) { // 检查浏览器是否支持 Web Share API
                // 浏览器环境下的分享API
                await navigator.share(shareData);
            } else {
                alert('分享功能不可用或未配置');
            }
        } catch (err) {
            console.error('[Error]: 分享链接时出错!', err);
            alert('[错误]: 分享链接时出错!');
        }
    });
}

2. Android Java 代码示例 (通过 JavascriptInterface 接收):

创建一个Java类作为JavaScript接口,并在其中实现分享逻辑。

import android.content.Context;
import android.content.Intent;
import android.webkit.JavascriptInterface;
import org.json.JSONObject;

public class JavaScriptShareInterface {
    private Context app_context;

    public JavaScriptShareInterface(Context context) {
        this.app_context = context;
    }

    @JavascriptInterface // 必须添加此注解,以便 JavaScript 可以调用此方法
    public void shareSearch(String javascript_data) {
        try {
            JSONObject search = new JSONObject(javascript_data);
            String title = search.getString("title");
            String text = search.getString("text");
            String url = search.getString("url");
            String content = title + "\n" + text + "\n\n" + url;

            Intent sendIntent = new Intent(Intent.ACTION_SEND);
            sendIntent.setType("text/plain");
            sendIntent.putExtra(Intent.EXTRA_TEXT, content);