Android开发之webview以及浏览器阻止了cookie问题的解决

10人浏览 / 0人评论 / 添加收藏

在Android webview的原生开发中,我们想在安卓app上展示网址页面。我们需要在layout中展示webview组件,代码中load相关的网址即可。

layout的xml文件,activity_main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.waiqin365.dhcloud.share.MainActivity">

<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

</RelativeLayout>

Activity中代码如下:
this.webView = findViewById(R.id.webview);
Intent intent = getIntent();
String url = intent.getStringExtra("url");
this.webView.loadUrl(url);

然后,在手机上启动运行调试。

这个时候会开启你开启javascript的支持。

然后补充如下的代码:

WebSettings webSettings = this.webView.getSettings();
webSettings.setJavaScriptEnabled(true);

这个时候会发现报如下的错误:“当前浏览器阻止了cookie,将影响页面的使用,请进入浏览器设置页面修改cookie设置。”

这个时候需要开启cookie的支持。补充代码如下:

WebSettings webSettings = this.webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);

CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);

if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.setAcceptThirdPartyCookies(this.webView,true);
}
}

// 允许跨域请求
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
webSettings.setAllowUniversalAccessFromFileURLs(true);
} else {
// 对于低于API 16的版本,使用如下方式
webSettings.setAllowUniversalAccessFromFileURLs(false);
}

 

全部评论