Android - 在 WebView 中选择文件按钮 [英] Android - Choose File button in WebView

查看:15
本文介绍了Android - 在 WebView 中选择文件按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WebView 中加载了一个页面时遇到了问题 - 我不会发布整个应用程序的代码,因为我的问题非常具体:我的 HTML 页面中的选择文件"按钮适用于 Android Studio 创建的模拟器,但不适用于其他地方.

I'm having a problem where I've got a page loaded in WebView - I'm not going to post code for the entire application, because my problem is very specific: the "Choose File" button in my HTML page works on the Android Studio created emulator, but nowhere else.

按钮运行此代码:

<input type='file' id='fileInput' accept='text/plain' onchange='openFile(event);'>
var openFile = function(event) {
        var input = event.target;

        var reader = new FileReader();
        reader.onload = function(e){
            /* various string parsing */
        };
        reader.readAsText(input.files[0]);
};

这在我的 API 23 模拟器上运行得非常好:单击该按钮会打开设备的默认文件选择器以选择一个文件.但是,在我的实际手机(即 API 16)上,单击此按钮没有任何作用.此外,在 API 18 的 Genymotion 模拟器上,单击按钮什么也不做.我能做些什么来解决这个问题吗?该按钮在我的手机和 Genymotion 模拟器上都不会产生错误消息,它只是坐在那里,没有任何反应.

This works perfectly fine on my emulator which is API 23: clicking the button opens the device's default File chooser to pick a file. However, on my actual phone, which is API 16, clicking this button does nothing. Furthermore, on a Genymotion emulator, which is API 18, clicking the button does nothing. Is there something I can do to fix this? The button produces no error messages on both my phone and the Genymotion emulator, it just sits there and nothing happens.

我需要应用程序在允许语音转文本的设备上运行,所以我不能只使用模拟器,随心所欲.

I need the app to work on a device that allows speech-to-text, so I can't only use the emulator, as much as I'd like to.

推荐答案

set WebChromeClient for Choose File

set WebChromeClient for Choose File

代码

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.apache.http.util.EncodingUtils;

public class BrowserScreen extends Activity {

    private WebView webView;
    private String url = "url";       

    private ValueCallback<Uri> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browser_activity);
        initFields();
        setListeners();        
    }               

    public void initFields() {
        // TODO Auto-generated method stub

        webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setAllowFileAccess(true);
    }    

    public void setListeners() {
        // TODO Auto-generated method stub

        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

                webView.loadUrl("about:blank");

                view.clearHistory();
            }        
        });

        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {

            }

            //The undocumented magic method override
            //Eclipse will swear at you if you try to put @Override here
            // 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.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        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.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

            }    
        });

            webView.loadUrl(url);    

        final MyJavaScriptInterface myJavaScriptInterface
                = new MyJavaScriptInterface(this);
        webView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub

        if (webView.canGoBack() == true) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }


    public class MyJavaScriptInterface {
        Context mContext;

        MyJavaScriptInterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void showToast(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
            // webView.loadUrl("javascript:document.getElementById("Button3").innerHTML = "bye";");
        }

        @JavascriptInterface
        public void openAndroidDialog() {
            AlertDialog.Builder myDialog
                    = new AlertDialog.Builder(BrowserScreen.this);
            myDialog.setTitle("DANGER!");
            myDialog.setMessage("You can do what you want!");
            myDialog.setPositiveButton("ON", null);
            myDialog.show();
        }   
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }
}

这篇关于Android - 在 WebView 中选择文件按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆