扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

Android WebView鏂囦欢涓婁紶濡備綍澶勭悊

扬州沐宇科技
2024-06-19 10:44:03
android

鍦ˋndroid WebView涓鐞嗘枃浠朵笂浼犵殑姝ラ濡備笅锛?/p>

  1. 璁剧疆WebChromeClient瀵硅薄锛氳澶勭悊鏂囦欢涓婁紶锛屽繀椤讳负WebView璁剧疆涓€涓猈ebChromeClient瀵硅薄骞堕噸鍐檕nShowFileChooser鏂规硶銆傚湪璇ユ柟娉曚腑锛屽彲浠ュ垱寤轰竴涓狥ileChooser瀵硅薄骞舵樉绀烘枃浠堕€夋嫨鍣ㄣ€?/li>
webView.setWebChromeClient(new WebChromeClient() {
    // For Android 4.1+
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
        mUploadMessage = uploadMsg;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent, "File Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    // For Android 5.0+
    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        mFilePathCallback = filePathCallback;
        Intent intent = fileChooserParams.createIntent();
        startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
        return true;
    }
});
  1. 澶勭悊鏂囦欢閫夋嫨缁撴灉锛氬湪Activity鐨刼nActivityResult鏂规硶涓鐞嗘枃浠堕€夋嫨缁撴灉锛屽苟灏嗛€夊畾鐨勬枃浠朵紶閫掔粰WebView銆?/li>
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == FILE_CHOOSER_RESULT_CODE) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            if (mUploadMessage == null)
                return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else {
            if (mFilePathCallback == null)
                return;
            mFilePathCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
            mFilePathCallback = null;
        }
    }
}
  1. 鍦╓eb椤甸潰涓皟鐢ㄦ枃浠朵笂浼狅細鍦╓eb椤甸潰涓皟鐢ㄦ枃浠朵笂浼犳椂锛屽彲浠ヤ娇鐢?code><input type="file">鏍囩鎴朖avaScript鏉ヨЕ鍙戞枃浠堕€夋嫨瀵硅瘽妗嗐€?/li>
<input type="file" id="fileInput" name="fileInput" />
<script>
    var fileInput = document.getElementById('fileInput');
    fileInput.addEventListener('change', function() {
        // Handle file selection
    });
</script>

閫氳繃浠ヤ笂姝ラ锛屾偍鍙互鍦ˋndroid WebView涓鐞嗘枃浠朵笂浼犳搷浣溿€傛偍鍙互鏍规嵁闇€瑕佷慨鏀逛唬鐮佷互閫傚簲鎮ㄧ殑鍏蜂綋瑕佹眰銆?/p>

扫码添加客服微信