【问题标题】:Do we need to change anything in usual webpage loader for loading an AMP (accelerate mobile page) webpage in Android?我们是否需要更改常规网页加载器中的任何内容以在 Android 中加载 AMP(加速移动页面)网页?
【发布时间】:2023-04-10 13:36:01
【问题描述】:

这是我的代码:

import android.app.Activity; 
import android.os.Bundle;
import android.webkit.WebView;

public class Main extends Activity { 
    private WebView mWebview; 
    @Override
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 

        mWebview = new WebView(this);
        mWebview.loadUrl("https://ampbyexample.com/");
        setContentView(mWebview); 
    } 
}

但是,它不会像通常那样快速加载 AMP 网页。它像普通网页一样加载。

此代码是否需要更改。

【问题讨论】:

    标签: java php android html amp-html


    【解决方案1】:

    最重要的是启用 javascript - AMP 运行时需要 javascript 才能工作。不过,您还可以做一些其他事情来改进在 Android 上的 web 视图中加载 AMP 页面:

    ...
    
    WebSettings webViewSettings = webView.getSettings();
    
    // Important: enable javascript
    webViewSettings.setJavaScriptEnabled(true);
    
    webViewSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    
    
    // enable 3P cookies (important when loading AMP pages via a cache)
    CookieManager cookieManager = CookieManager.getInstance();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
              && !cookieManager.acceptCookie()) {
      cookieManager.setAcceptThirdPartyCookies(mWebView, true);
    }
    
    // enable local storage
    webViewSettings.setDomStorageEnabled(
    webViewSettings.setDatabaseEnabled(
    if (Build.VERSION.SDK_INT < 
      webViewSettings.setDatabasePath("/data/data/" + mActivity.getPackageName() + "/");
    }
    
    // set the referrer to your app
    Map<String, String> extraHeaders = new HashMap<>();
    extraHeaders.put("Referer", 
        Intent.URI_ANDROID_APP_SCHEME + "//" + context.getPackageName());
    
    webView.loadUrl(url, extraHeaders);
    

    最后,您可以通过 AMP 缓存加载 AMP 页面,该缓存在加载 AMP 页面时会执行额外的优化(请参阅this article,了解如何构建 URL)。

    请注意:缓存只会加载有效的 AMP。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 2012-10-07
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多