uni-app.04.发布成H5后,uni.chooseImage方法在android WebView上无法使用

Posted 潮汐先生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了uni-app.04.发布成H5后,uni.chooseImage方法在android WebView上无法使用相关的知识,希望对你有一定的参考价值。

发布成H5后,uni.chooseImage方法在android WebView上无法使用

引言

经过三个星期的折腾,uni-app的编码阶段宣告结束,正式进入到测试阶段。由于app有个功能需要引入第三方的android原生SDK,经过前期的测试论证决定将第三方的android原生sdk功能写在android的壳子里,在android的壳子里引入webview,然后将uni-app发布成H5,然后在webview里面调用H5页面。多么完美的方案,但是理想很丰满,显示很骨感啊,刚进入测试就发现uni-app的选择图片的方法uni.chooseImage死活不起作用。于是在DCloud问答社区搜索解决方案,看到这么一个帖子编译成H5后,uni.chooseImage方法在android WebView上无法使用,一毛一样有木有?o(╥﹏╥)o

官方给出的方案是让Webview支出图片选择,既然有了解决方案那就开干吧

解决方案

首先根据官方的提示在度娘上搜了一通,有这么篇文章深坑之Webview,解决H5调用android相机拍照和录像,不得不说大佬还是真的多啊,按照大佬的提示加上自己的需求来改造一下自己的webview(这里只贴出跟本功能相关的代码)

	private Uri imageUri;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int PHOTO_REQUEST = 100;
    private final static int VIDEO_REQUEST = 120;
    private boolean videoFlag = false;
    private WebChromeClient webChromeClient = new WebChromeClient() 
        public void onProgressChanged(WebView view, int newProgress) 
            try 
                onProgress(view, newProgress);
             catch (Exception e) 
                e.printStackTrace();
            
        

        // For Android 3.0-
        public void openFileChooser(ValueCallback<Uri> uploadMsg) 
            Log.d(TAG, "openFileChoose(ValueCallback<Uri> uploadMsg)");
            mUploadMessage = uploadMsg;
            if (videoFlag) 
                recordVideo();
             else 
                takePhoto();
            
        

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) 
            Log.d(TAG, "openFileChoose( ValueCallback uploadMsg, String acceptType )");
            mUploadMessage = uploadMsg;
            if (videoFlag) 
                recordVideo();
             else 
                takePhoto();
            
        

        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) 
            Log.d(TAG, "openFileChoose(ValueCallback<Uri> uploadMsg, String acceptType, String capture)");
            mUploadMessage = uploadMsg;
            if (videoFlag) 
                recordVideo();
             else 
                takePhoto();
            
        

		// 本人以为5.0以前的大可不必处理,现在新建的android项目minSDK都建议22(也就是android5.0)起步了,再说了目前的环境先5.0以前的系统还真不好找,除了老年机
        // For Android 5.0+
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) 
            Log.d(TAG, "onShowFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)");
            mUploadCallbackAboveL = filePathCallback;
            if (videoFlag) 
                recordVideo();
             else 
                takePhoto();
            
            return true;
        
    ;

 	/**
     * 拍照
     */
   	private void takePhoto() 
       new ActionSheetDialog(MainActivity.this)
               .builder()
               .setCancelable(false)
               .setCanceledOnTouchOutside(false)
               .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                   new ActionSheetDialog.OnSheetItemClickListener() 
                       @Override
                       public void onClick(int which) 
                           File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
                           imageUri = Uri.fromFile(fileUri);
                           if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) 
                               imageUri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
                           
                           PhotoUtil.takePicture(MainActivity.this, imageUri, PHOTO_REQUEST);
                       
               )
               .addSheetItem("从相册选择", ActionSheetDialog.SheetItemColor.Blue,
                   new ActionSheetDialog.OnSheetItemClickListener() 
                       @Override
                       public void onClick(int which) 
                           PhotoUtil.openPic(MainActivity.this, PHOTO_REQUEST);
                       
               )
               .addSheetItem("取消", ActionSheetDialog.SheetItemColor.Red,
                   new ActionSheetDialog.OnSheetItemClickListener() 
                       @Override
                       public void onClick(int which) 
                           if (mUploadMessage != null) 
                               mUploadMessage.onReceiveValue(null);
                               mUploadMessage = null;
                           
                           if (mUploadCallbackAboveL != null) 
                               mUploadCallbackAboveL.onReceiveValue(null);
                               mUploadCallbackAboveL = null;
                           
                       
               )
               .show();
    

	/**
     * 录像
     */
    private void recordVideo() 
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        //限制时长
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
        //开启摄像机
        startActivityForResult(intent, VIDEO_REQUEST);
    

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST) 
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) 
                onActivityResultAboveL(requestCode, resultCode, data);
             else if (mUploadMessage != null) 
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            
         else if (requestCode == VIDEO_REQUEST) 
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;

            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) 
                if (resultCode == RESULT_OK) 
                    mUploadCallbackAboveL.onReceiveValue(new Uri[]result);
                    mUploadCallbackAboveL = null;
                 else 
                    mUploadCallbackAboveL.onReceiveValue(new Uri[]);
                    mUploadCallbackAboveL = null;
                

             else if (mUploadMessage != null) 
                if (resultCode == RESULT_OK) 
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                 else 
                    mUploadMessage.onReceiveValue(Uri.EMPTY);
                    mUploadMessage = null;
                

            
        
    

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) 
        if (requestCode != PHOTO_REQUEST || mUploadCallbackAboveL == null) 
            return;
        
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) 
            showToast("正在上传,请稍后……");
            if (data == null) 
                results = new Uri[]imageUri;
             else 
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) 
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) 
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    
                

                if (dataString != null)
                    results = new Uri[]Uri.parse(dataString);
            
         else 
            showToast("没有选择图片!");
        
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
    

    private void showToast(String message) 
        Toast toast = Toast.makeText(this, null, Toast.LENGTH_LONG);
        toast.setText(message);
        toast.show();
    

	private WebViewClient webViewClient = new WebViewClient() 
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) 
        	// 我这里主要用到的是拍照和选择图片,没有录像的功能,这个功能本可以去掉的,但是我很懒
            if (!TextUtils.isEmpty(url)) 
                videoFlag = url.contains("video");
            

            if (url.trim().startsWith("tel")) 
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
             else 
                String port = url.substring(url.lastIndexOf(":") + 1, url.lastIndexOf("/"));//尝试要拦截的视频通讯url格式(808端口):【http://xxxx:808/?roomName】
                if (port.equals("808")) //特殊情况【若打开的链接是视频通讯地址格式则调用系统浏览器打开】
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                 else //其它非特殊情况全部放行
                    view.loadUrl(url);
                
            
            return true;
        

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) 
            try 
                onPageBegin(view, url, favicon);
             catch (Exception e) 
                e.printStackTrace();
            
        

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) 
            super.onReceivedError(view, errorCode, description, failingUrl);
            isLoadSuccess = false;
            if (isLoadSuccess) 
                layoutEmpty.setVisibility(View.GONE);
             else 
                layoutEmpty.setVisibility(View.VISIBLE);
            
        

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) 
            super.onReceivedError(view, request, error);
            isLoadSuccess = false;
            if (isLoadSuccess) 
                layoutEmpty.setVisibility(View.GONE);
             else 
                layoutEmpty.setVisibility(View.VISIBLE);
            
        

        @Override
        public void onPageFinished(WebView view, String url) 
            try 
                onPageEnd(view, url);
             catch (Exception e) 
                e.printStackTrace();
            
        
    ;

至于代码中用到的PhotoUtil上面提到的大佬的博客中已经给出了,以防万一这里贴一下

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class PhotoUtil 
    private static final String TAG = "PhotoUtil";

    /**
     * @param activity    当前activity
     * @param imageUri    拍照后照片存储路径
     * @param requestCode 调用系统相机请求码
     */
    public static void takePicture(Activity activity, Uri imageUri, int requestCode) 
        //调用系统相机
        使用HBuilderX将vue项目打包成app

uniapp微信小程序跳转H5后video自动播放

微信公众号输入关键字后返回一个H5分享链接怎么实现?

移动端中 H5输入框在弹起键盘后被遮挡

怎么把h5放到ppt里

h5_PC上传图片