HTML调用原生相册

public class FileChooser {

    private static FileChooser FILE_CHOOSER;

    private Activity mActivity;
    private final int FILE_SELECT_CODE = 1;
    private ValueCallback mUploadCallbackBelow;
    private ValueCallback mUploadCallbackAboveL;

    public static FileChooser get(Activity activity){

        if (FILE_CHOOSER == null){
            FILE_CHOOSER = new FileChooser(activity);
        }

        return FILE_CHOOSER;
    }

    public FileChooser(Activity activity) {
        mActivity = activity;
    }

    /**
     * API >= 21(Android 5.0.1)
     */
    public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback,
                                     WebChromeClient.FileChooserParams fileChooserParams) {
        mUploadCallbackAboveL = filePathCallback;
        takeImage();
        return true;
    }

    /**
     * 16(Android 4.1.2) <= 20(Android 4.4W.2)
     */
    public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
        mUploadCallbackBelow = uploadMsg;
        takeImage();
    }

    private void takeImage() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        mActivity.startActivityForResult(Intent.createChooser(i, "File Browser"), FILE_SELECT_CODE);
    }

    // 接收图片回调
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK && data != null) {
            if (mUploadCallbackBelow != null) {
                chooseBelow(resultCode, data);
            } else if (mUploadCallbackAboveL != null) {
                chooseAbove(resultCode, data);
            }
        }
    }

    /**
     * Android API < 21(Android 5.0)
     */
    private void chooseAbove(int resultCode, Intent data) {
        Uri uriData = data.getData();
        if (uriData != null) {
            mUploadCallbackAboveL.onReceiveValue(new Uri[]{uriData});
        } else {
            mUploadCallbackAboveL.onReceiveValue(null);
        }
    }

    /**
     * 16(Android 4.1.2) <= 20(Android 4.4W.2)
     */
    private void chooseBelow(int resultCode, Intent data) {
        Uri uri = data.getData();
        if (uri != null) {
            mUploadCallbackBelow.onReceiveValue(uri);
        } else {
            mUploadCallbackBelow.onReceiveValue(null);
        }
    }
}

你可能感兴趣的:(HTML调用原生相册)