Android与js交互拍照上传资料

应用场景:h5通知android端拍照,选相册,然后将图片路径上传成功之后,获取到网络路径,将此路径返还给h5界面,并展示出来。 
android与js快速交互 
效果图如下: 
这里写图片描述 
这里写图片描述

1.在Activity类中,通过webview拦截协议,开始拍照或选择相册。

    mWebView = (WebView) findViewById(R.id.wv); 
//设置webview可以与js交互 
    mWebView.getSettings().setJavaScriptEnabled(true); 
//设置webview加载本地h5页面 
    mWebView.loadUrl(“file:///android_asset/choosePic.html”); 
//设置监听,获取webview访问的url 
    mWebView.setWebViewClient(new WebViewClient() { 
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
        // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边 
                if(url.contains(“hgj://take/photo”)){
                //js定义的协议,android用webview进行拦截 然后本地调用拍照等功能 
                    showPopupWindow((LinearLayout) findViewById(R.id.act_index)); 
                }else {
                view.loadUrl(url);
            }
            return true;
        }
        @Override
        public void onPageFinished(WebView view, String url) {

        }
    });

2. 注册js接口,JSInterface是自定义的类,里面放的方法必须与js中的方法一致,参数二也是与js协定的,必须与js保持一致。

  mWebView.addJavascriptInterface(new JSInterface(), "hgj");
//js接口类
private class JSInterface {

    @JavascriptInterface
    public void acceptUrl(String imgUrl) {//此方法是将android端获取的url返给js

    }
     @JavascriptInterface
        public void fnUrl(String s) {
           //js可以调用此方法 将s值传给android端,然后android端进行相应的操作,此参数可以是任意类型的
        }
          @JavascriptInterface
        public void  fnId(String received){
        //android 调用js js会回传参数
            Log.i("received--","---"+received);
        }

}

3.拍照、上传图片相关方法

  //确认上传图片
    private void upload(String path) throws FileNotFoundException {
        //此处可以写入上传图片的方法  这里就直接将拍照和选择相册得到的本地路径返回
        url=path;
        Message msg = new Message();
        msg.what = 0;
        mHandler1.sendMessage(msg);
    }
/*
* 相册或相机
* */
private void showPopupWindow(LinearLayout parent) {
    if (popWindow == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.pop_select_photo, null);
            // 相机/相册/取消选择界面
                 popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
                initPop(view);// 初始化popwindow参数
    }
    popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
    popWindow.setFocusable(true);
    popWindow.setOutsideTouchable(true);
    popWindow.setBackgroundDrawable(new BitmapDrawable());
    popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
}

// 初始化popwindow参数
public void initPop(View view) {
    photograph = (TextView) view.findViewById(R.id.photograph);// 拍照
    albums = (TextView) view.findViewById(R.id.albums);// 相册
    cancel = (LinearLayout) view.findViewById(R.id.cancel);// 取消
    // 相机拍照监听
    photograph.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            popWindow.dismiss();
            photoSaveName = String.valueOf(System.currentTimeMillis()) + ".png";
            photoSavePath = Environment.getExternalStorageDirectory() + "/usershg/cache/";
            Uri imageUri = null;
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            imageUri = Uri.fromFile(new File(photoSavePath, photoSaveName));
            openCameraIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(openCameraIntent, PHOTOTAKE);
        }
    });
    // 相册获取监听
    albums.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            popWindow.dismiss();
            Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
            openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(openAlbumIntent, PHOTOZOOM);
        }
    });
    // 取消监听
    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            popWindow.dismiss();

        }
    });
}

@SuppressLint("NewApi")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        return;
    }
    Uri uri = null;
    switch (requestCode) {
        case PHOTOZOOM:// 相册
            if (data == null) {
                return;
            }
            uri = data.getData();
            path = getImageAbsolutePath(this, uri);
            //获取到图片路径,开始上传
            try {
                upload(path);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            break;
        case PHOTOTAKE:// 拍照
            path = photoSavePath + photoSaveName;
             //获取到图片路径,开始上传
            try {
                upload(path);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            break;
        default:
            break;
    }
}

/**
 * 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换
 *
 * @param
 * @param imageUri
 * @author yaoxing
 * @date 2014-10-12
 */
@TargetApi(19)
public static String getImageAbsolutePath(Activity context, Uri imageUri) {
    if (context == null || imageUri == null)
        return null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
        if (isExternalStorageDocument(imageUri)) {
            String docId = DocumentsContract.getDocumentId(imageUri);
            String[] split = docId.split(":");
            String type = split[0];
            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
        } else if (isDownloadsDocument(imageUri)) {
            String id = DocumentsContract.getDocumentId(imageUri);
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        } else if (isMediaDocument(imageUri)) {
            String docId = DocumentsContract.getDocumentId(imageUri);
            String[] split = docId.split(":");
            String type = split[0];
            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            String selection = MediaStore.Images.Media._ID + "=?";
            String[] selectionArgs = new String[]{split[1]};
            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    } // MediaStore (and general)
    else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
        // Return the remote address
        if (isGooglePhotosUri(imageUri))
            return imageUri.getLastPathSegment();
        return getDataColumn(context, imageUri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
        return imageUri.getPath();
    }
    return null;
}

public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    String column = MediaStore.Images.Media.DATA;
    String[] projection = {column};
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
public static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}

4.拍照成功获取url后传给js

 //此处将拍照或选择相册返回的url传给js
           mWebView.loadUrl("javascript:acceptUrl('" + url + "')");

5. js给android传数据

js只需要调用window.hgj.fnId(received);就可以了。
hgj:是我们之前android和js定的,如mWebView.addJavascriptInterface(new JSInterface(), "hgj");中的最后一个参数
fnId()是方法名,js把参数传进去,我们android端只要写好这个方法,直接loadUrl获取参数就可以了,如wv.loadUrl("javascript:fnId()");

h5页面: 
这里写图片描述

源码位置:https://download.csdn.net/download/feitailang/10839514
源码项目截图: 
这里写图片描述

原文地址:https://www.cnblogs.com/yelanggu/p/9593507.html