本Markdown编辑器使用StackEdit修改而来,用它写博客,将会带来全新的体验哦:
package com.dwb.renrendaipai.mywebview;
import android.net.Uri;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
/**解决H5图片上传问题
* Created by dwb on 2018/6/15.
*/
public class AotuWebChromeClient extends WebChromeClient{
private OpenFileChooserCallBack mOpenFileChooserCallBack;
public AotuWebChromeClient(OpenFileChooserCallBack openFileChooserCallBack) {
mOpenFileChooserCallBack = openFileChooserCallBack;
}
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mOpenFileChooserCallBack.openFileChooserCallBack(uploadMsg, acceptType);
}
public void openFileChooser(ValueCallback uploadMsg) {
openFileChooser(uploadMsg, "");
}
public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback,
FileChooserParams fileChooserParams) {
return mOpenFileChooserCallBack.openFileChooserCallBackAndroid5(webView, filePathCallback, fileChooserParams);
}
public interface OpenFileChooserCallBack {
// for API - Version below 5.0.
void openFileChooserCallBack(ValueCallback uploadMsg, String acceptType);
// for API - Version above 5.0 (contais 5.0).
boolean openFileChooserCallBackAndroid5(WebView webView, ValueCallback filePathCallback,
FileChooserParams fileChooserParams);
}
}
Activity代码
/**零元下单 图片上传
* Created by dwb on 2018/6/15.
*/
public class AoTuWebviewActivity extends AppCompatActivity{
@BindView(R.id.toorbar_layout_main_back)
LinearLayout toorbar_layout_main_back;
@BindView(R.id.toorbar_txt_main_title)
TextView toorbar_txt_main_title;
@BindView(R.id.webview)
WebView webview;
@BindView(R.id.progressbar)
ProgressBar progressbar;
private Intent mintent;
private WebSettings webSettings;
private String url, title;
///图片上传///////
private ValueCallback mUploadMsgForAndroid5;
private ValueCallback mUploadMsg;
private final static int FILECHOOSER_RESULTCODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
DSLApplication.getInstance().addActivity(this);
setContentView(R.layout.shouyeintroduce);
ButterKnife.bind(this);
mintent = getIntent();
url = mintent.getStringExtra("url");
title = mintent.getStringExtra("title");
toorbar_txt_main_title.setText(title);
init();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
if (mUploadMsg != null) {
mUploadMsg.onReceiveValue(null);
}
if (mUploadMsgForAndroid5 != null) { // for android 5.0+
mUploadMsgForAndroid5.onReceiveValue(null);
}
return;
}
switch (requestCode) {
case FILECHOOSER_RESULTCODE: {
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
if (mUploadMsg == null) {
return;
}
String sourcePath = getRealFilePath(this,data.getData());
if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
break;
}
Uri uri = Uri.fromFile(new File(sourcePath));
mUploadMsg.onReceiveValue(data.getData());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (mUploadMsgForAndroid5 == null) { // for android 5.0+
return;
}
String sourcePath = getRealFilePath(this,data.getData());
if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
break;
}
// Uri uri = Uri.fromFile(new File(sourcePath));
Uri imageFileUri = FileProvider.getUriForFile(context, "com.dwb.fileprovider", new File(sourcePath));//通过FileProvider创建一个content类型的Uri
mUploadMsgForAndroid5.onReceiveValue(new Uri[]{imageFileUri});
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
private void init() {
//WebView加载web资源
webview.loadUrl(url);
webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);//启用加速,否则滑动界面不流畅
webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);//关键点
webSettings.setDomStorageEnabled(true);
webSettings.setDefaultTextEncodingName("UTF-8");
webSettings.setAllowContentAccess(true); // 是否可访问Content Provider的资源,默认值 true
webSettings.setAllowFileAccess(true); // 是否可访问本地文件,默认值 true
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
webSettings.setLoadWithOverviewMode(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setBuiltInZoomControls(true); // 设置显示缩放按钮
// webSettings.setAppCacheEnabled(true);//是否使用缓存
webSettings.setSupportZoom(true); // 支持缩放
//覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为,使网页用WebView打开
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
//返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
if (url.contains("pages/user/all_demand.jsp")){
Intent intent=new Intent(AoTuWebviewActivity.this, MainActivity.class);
DSLContants.nums=4;
startActivity(intent);
finish();
}else {
view.loadUrl(url);
}
return false;
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
view.loadUrl("file:///android_asset/error.html");//加载本地网页的路径
}
});
webview.setWebChromeClient(new AotuWebChromeClient(new AotuWebChromeClient.OpenFileChooserCallBack() {
@Override
public void openFileChooserCallBack(ValueCallback uploadMsg, String acceptType) {
mUploadMsg=uploadMsg;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, FILECHOOSER_RESULTCODE);
}
@Override
public boolean openFileChooserCallBackAndroid5(WebView webView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
mUploadMsgForAndroid5=filePathCallback;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, FILECHOOSER_RESULTCODE);
return true;
}
}) {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress == 100) {
// 网页加载完成
progressbar.setVisibility(View.GONE);
} else {
// 加载中
if (progressbar.getVisibility()==View.GONE){
progressbar.setVisibility(View.VISIBLE);
}
progressbar.setProgress(newProgress);
}
}
});
}
@OnClick(R.id.toorbar_layout_main_back)
public void onViewClicked() {
finish();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
/**
* 返回键
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webview.canGoBack()) {
webview.goBack();
return true;
}
finish();
}
return super.onKeyDown(keyCode, event);
}
/**
* Try to return the absolute file path from the given Uri
*
* @param context
* @param uri 获取系统相册path
* @return the file path or null
*/
public static String getRealFilePath(final Context context, final Uri uri ) {
if ( null == uri ) return null;
final String scheme = uri.getScheme();
String data = null;
if ( scheme == null )
data = uri.getPath();
else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
data = uri.getPath();
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
if ( null != cursor ) {
if ( cursor.moveToFirst() ) {
int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
if ( index > -1 ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}
}
注意下面代码 return true 别return false 不让选择图片后报异常
@Override
public boolean openFileChooserCallBackAndroid5(WebView webView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
mUploadMsgForAndroid5=filePathCallback;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, FILECHOOSER_RESULTCODE);
return true;
}