android - 如何从 webview 上传图片?

标签 android android-webview

我的应用程序 (Android 4.4.4+) 中嵌入的 webview 有问题。在页面上有一个“上传图片”按钮,我使用 openFileChooser 进行管理。

在某些设备上,当我点击 WebView 中的“上传图片”按钮时,相机应用程序启动,我的应用程序被销毁。拍完照片后我的应用程序被重新创建,我恢复了 webview 状态(保存在 onSaveInstanceState 中)并调用了 onActivityResult()。问题是包含 ValueCallBack 的变量 mUploadMessage 为空,因此我无法调用 ValueCallBack.onReceiveValue() 来提供 WebView 的图像 URI。

// openFileChooser for Android 3.0+ to 4.4
// WARNING: the openFileChooser works in version 4.4 only for 4.4.3+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
    // Update message
    mUploadMessage = uploadMsg;
    fileChooserManagement(FILECHOOSER_RESULTCODE);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    webview.saveState(outState);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        // Restore last state
        webview.restoreState(savedInstanceState);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Do not test the resultCode, because it's mandatory to enter the 'if' and to call the
    // onReceiveValue even with null. Otherwise the openFileChooser will not be called anymore.
    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (this.mUploadMessage == null) {
            Log.i("myApp", "onActivityResult mUploadMessage is null");
            return;
        }
        mUploadMessage.onReceiveValue(processPicture(resultCode, data));
        mUploadMessage = null;
    }
}

有一个类似的话题here ,但问题是“我不明白如何保存 webview 状态并恢复它。如果我在 onRestoreInstanceState() 中恢复它,页面不会从相机拍摄照片。你能举个例子吗?”没有答案。

谢谢大家的帮助!

最佳答案

我知道你没有在你的代码中的任何地方实现 webview 客户端。您需要同时实现 webview 和使用 web chrome 客户端类来处理 android 应用程序上的文件上传。此外,您应该覆盖 url 加载。此外,您需要添加互联网访问权限和从外部存储读取权限。您可以阅读更多内容并下载演示相同 here 的演示 。希望对你有帮助

关于android - 如何从 webview 上传图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34354119/

相关文章:

java - 如果我滚动如何保存复选框选中的项目

android - Gradle 和嵌套的非传递依赖

java - Android 与 subview 组一起旋转

javascript - Android WebView - Javascript 不会触发回调函数

android - Android webview 中的所见即所得

android - 从服务调用时 Activity 重新启动

java - 在 Android 的 SQLite 数据库中保存 ArrayList

android - "light-weight"协程如何真正适用于真实世界的 Android 开发?

android - 在放大后使用 webview 在 Android 中显示 svg 不会缩小

Android WebView 未加载 URL