这是我的代码:
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网页的速度不如通常。它的加载方式像通常的网页一样。
此代码是否需要任何更改。
最重要的是启用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页面时,AMP缓存会执行其他优化(有关如何构造URL的信息,请参见this article)。
请注意:缓存将仅加载有效的AMP。