美文网首页
Android使用WebView支持html上传图片

Android使用WebView支持html上传图片

作者: i宁静的鱼 | 来源:发表于2019-08-07 16:57 被阅读0次

    Android使用WebView时,html页面的上传失效了,需要android端做一些配合。

    package com.iefeel.xuexi;
    
    import android.Manifest;
    import android.app.Activity;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.support.annotation.NonNull;
    import android.support.annotation.RequiresApi;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.webkit.JsResult;
    import android.webkit.ValueCallback;
    import android.webkit.WebChromeClient;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.ProgressBar;
    import android.widget.Toast;
    
    import com.yzq.zxinglibrary.android.CaptureActivity;
    import com.yzq.zxinglibrary.common.Constant;
    
    import java.io.File;
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
    
        public WebView webview;
        public static final int FILECHOOSER_RESULTCODE_5 = 12;
        public static final int FILECHOOSER_RESULTCODE = 13;
        public WebChromeClient.FileChooserParams  mfileChooserParams;
        public ValueCallback<Uri[]> umUploadMessages;
        public ValueCallback<Uri> mUploadMessage;
        public static final int REQUEST_CODE_SCAN = 1;
        private String xdomain = "http://xuexi.iefeel.com/ydsite/default/index";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            webview = new WebView(this);
            //支持Js
            webview.getSettings().setJavaScriptEnabled(true);
            //允许js弹出窗口
            webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            //设置是否开启DOM存储API权限,默认false,未开启,设置为true,WebView能够使用DOM storage API
            webview.getSettings().setDomStorageEnabled(true);
            //设置默认编码
            webview.getSettings().setDefaultTextEncodingName("UTF-8");
            //开启数据库功能
            webview.getSettings().setDatabaseEnabled(true);
            //开启web缓存功能
            webview.getSettings().setAppCacheEnabled(false);
            //设置在WebView内部是否允许访问文件,默认允许访问。
            webview.getSettings().setAllowFileAccess(true);
            //设置缓存模式
            webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            //设置WebView是否使用viewport,当该属性被设置为false时,加载页面的宽度总是适应WebView控件宽度;
            //当被设置为true,当前页面包含viewport属性标签,在标签中指定宽度值生效,如果页面不包含viewport标签,
            //无法提供一个宽度值,这个时候该方法将被使用。
            webview.getSettings().setUseWideViewPort(true);
            //必须设置setWebViewClient  自定义的继承于WebViewClient的类就是用来拦截url处理一些与H5交互的时候的逻辑
            webview.setWebViewClient(new WebViewClient(){
    
                //此方法可以使H5在WebView中显示,而不是手机浏览器
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
    
                //访问url开始时候触发
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                }
    
                //访问url结束时候触发
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                }
    
                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    // TODO Auto-generated method stub
                    super.onReceivedError(view, errorCode, description, failingUrl);
                }
    
                public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                    Log.d("MyApplication", message + " -- From line " + lineNumber + " of " + sourceID);
                }
    
            });
            webview.setWebChromeClient(new WebChromeClient(){
                public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    builder.setTitle("系统提示")
                            .setMessage(message)
                            .setPositiveButton("确定", null)
                            .setCancelable(false)
                            .create()
                            .show();
                    result.confirm();
                    return true;
                }
    
                public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    builder.setTitle("系统提示")
                            .setMessage(message)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    result.confirm();
                                }
                            }).setNeutralButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            result.cancel();
                        }
                    })
                            .create()
                            .show();
                    return true;
                }
    
                @Override
                public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                    umUploadMessages = filePathCallback;
                    mfileChooserParams = fileChooserParams;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.putExtra("return-data", true);
                    i.setType("image/*");
                    i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(Intent.createChooser(i, "选择相册"), FILECHOOSER_RESULTCODE_5);
                    return true;
                }
    
                // For Android 3.0
                public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                    mUploadMessage = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.putExtra("return-data", true);
                    i.setType("image/*");
                    i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(Intent.createChooser(i, "选择相册"), FILECHOOSER_RESULTCODE);
                }
    
                // For Android > 4.1
                public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                    mUploadMessage = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.putExtra("return-data", true);
                    i.setType("image/*");
                    i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(Intent.createChooser(i, "选择相册"),
                            FILECHOOSER_RESULTCODE);
                }
    
                // Android 3.0 +
                public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                    mUploadMessage = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.putExtra("return-data", true);
                    i.setType("image/*");
                    i.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(Intent.createChooser(i, "选择相册"), FILECHOOSER_RESULTCODE);
                }
            });
            webview.loadUrl(xdomain + "?is_app_client=1&rnum=" + System.currentTimeMillis());
            setContentView(webview);
        }
    
        //创建菜单
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menu,menu);
            return true;
        }
    
        //菜单点击事件
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()){
                case R.id.id_about_us: //关于
                    String version = getVersionName(this);
                    AlertDialog aboutDialog = new AlertDialog.Builder(this).create();
                    aboutDialog.setTitle("鱼知凡在线学习系统");
                    aboutDialog.setMessage("当前版本:" + version);
                    aboutDialog.show();
                    break;
                case R.id.id_scan_some: //扫码
                    checkPermission();
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, CaptureActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                    break;
                case R.id.id_close_app: //退出
                    AlertDialog exitDialog = new AlertDialog.Builder(this).create();
                    exitDialog.setTitle("系统提示");
                    exitDialog.setMessage("确定要退出吗");
                    exitDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                    exitDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(MainActivity.this, "欢迎回来", Toast.LENGTH_SHORT).show();
                        }
                    });
                    exitDialog.show();
                    break;
                default:
                    break;
            }
            return true;
        }
    
        //监听退出动作
        @Override
        public void onBackPressed(){
            if(webview.canGoBack()){
                webview.goBack();
                return;
            }else{
                AlertDialog exitDialog = new AlertDialog.Builder(this).create();
                exitDialog.setTitle("系统提示");
                exitDialog.setMessage("确定要退出吗");
                exitDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                exitDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "欢迎回来", Toast.LENGTH_SHORT).show();
                    }
                });
                exitDialog.show();
                return;
            }
        }
    
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == FILECHOOSER_RESULTCODE) {
                if (null == mUploadMessage) return;
                if (null == data){
                    mUploadMessage.onReceiveValue(null);
                    mUploadMessage = null;
                }else{
                    Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                }
            }else  if (requestCode == FILECHOOSER_RESULTCODE_5){// 5.0适配,主要是因为5.0的返回参数不同。
                // 处理5.0的callback
                if (umUploadMessages != null) {
                    if (null != data) { // 5.0的处理方式不同,要注意。
                        ArrayList<String> resultList = data.getStringArrayListExtra("data");
                        umUploadMessages.onReceiveValue(mfileChooserParams.parseResult(resultCode, data));
                        umUploadMessages = null;
                    } else {
                        umUploadMessages.onReceiveValue(null);
                    }
                }
            }else if(requestCode == REQUEST_CODE_SCAN){//扫码观看
                if(resultCode == RESULT_OK){
                    String result = data.getStringExtra(Constant.CODED_CONTENT);
                    webview.loadUrl(result);
                }
            }
        }
    
        private void checkPermission() {
            if (Build.VERSION.SDK_INT >= 23) {
                int checkCallPhonePermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA);
                if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CAMERA,Manifest.permission.VIBRATE},333);
                    return;
                }else{ }
            } else { }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    
        //获取版本名
        public static String getVersionName(Context context) {
            return getPackageInfo(context).versionName;
        }
    
        //获取版本号
        public static int getVersionCode(Context context) {
            return getPackageInfo(context).versionCode;
        }
    
        //通过PackageInfo得到的想要启动的应用的包名
        private static PackageInfo getPackageInfo(Context context) {
            PackageInfo pInfo = null;
            try {
                //通过PackageManager可以得到PackageInfo
                PackageManager pManager = context.getPackageManager();
                pInfo = pManager.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
                return pInfo;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return pInfo;
        }
    
    }
    

    其中用到的菜单文件menu.xml如下

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:id="@+id/id_about_us" android:title="关于"/>
        <item android:id="@+id/id_scan_some" android:title="扫码"/>
        <item android:id="@+id/id_close_app" android:title="退出"/>
    </menu>
    

    其中还用到了扫码功能,需要添加以下依赖包

    implementation 'com.github.yuzhiqiang1993:zxing:2.2.8'
    

    相关文章

      网友评论

          本文标题:Android使用WebView支持html上传图片

          本文链接:https://www.haomeiwen.com/subject/fkhadctx.html