android webView示例代码(使用时打开本地html跨域、type=file 选择文件打不开问题)
1、 当我使用 android webview 打开本地 html 时,页面的 layui 的路由 使用 ajax 读取html、less文件采用了发请求的方式,所以出现了跨域问题。2、h5 type=file选择文件打不开。
·
1、 当我使用 android webview 打开本地 html 时,页面的 layui 的路由 使用 ajax 读取html、less文件采用了发请求的方式,所以出现了跨域问题。
2、h5 type=file 选择文件打不开
解决上面问题,webView 代码示例:
public class MainActivity extends AppCompatActivity {
public WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView1);
setUpView("file:///android_asset/www/login.html");
}
@SuppressLint("SetJavaScriptEnabled")
public void setUpView(String url) {
//加载需要显示的网页
// webView = new WebView(this); 不在xml中创建webview 也可以在这new
// setContentView(webView);
webView.loadUrl(url);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true); //设置WebView属性,运行执行js脚本
// webSettings.setSafeBrowsingEnabled(false);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setDomStorageEnabled(true);
webSettings.setUseWideViewPort(true);//设定支持viewport
webSettings.setLoadWithOverviewMode(true);//自适应屏幕
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportZoom(true);//设定支持缩放
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不读取缓存
// webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);//api 16 不支持
webView.setBackgroundColor(ContextCompat.getColor(this,android.R.color.transparent));
// webView.setBackgroundResource(R.color.black);
webView.setWebViewClient(webClient); //设置Web视图
try {//本地HTML里面有跨域的请求 原生webview需要设置之后才能实现跨域请求(less、layui路由)
if (Build.VERSION.SDK_INT >= 16) {
Class<?> clazz = webView.getSettings().getClass();
Method method = clazz.getMethod(
"setAllowUniversalAccessFromFileURLs", boolean.class);
if (method != null) {
method.invoke(webView.getSettings(), true);
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// 解决webView 不支持h5 type=file 选择文件弹框
webView.setWebChromeClient(new WebChromeClient() {
// For 3.0+ Devices (Start)
// onActivityResult attached before constructor
protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
// For Lollipop 5.0+ Devices
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try
{
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e)
{
uploadMessage = null;
Toast.makeText(getBaseContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
}
WebViewClient webClient = new WebViewClient() {
//设置打开网页时,不调用系统浏览器进行打开,而是在本WebView中直接显示。
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
// Toast.makeText(MainActivity.this, "开始加载", Toast.LENGTH_SHORT).show();
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//加载开始的操作
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//加载结束的操作
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
//加载页面的服务器出现错误时(如404)调用
System.out.println("资源加载和页面打开错误时都会进入");
//回调失败的相关操作
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
}
};
}
添加访问网络权限(AndroidManifest.xml)
<uses-permission android:name="android.permission.INTERNET"/>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
更多推荐
已为社区贡献14条内容
所有评论(0)