使用 webview 浏览照片库 [英] Using a webview to browse the photo gallery

查看:19
本文介绍了使用 webview 浏览照片库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Min SDK API 15

你好

我使用的网页视图上有一个按钮,可以浏览应用程序照片库.

I using a webview that has a button on it that will browse the apps photo gallery.

但是,当在 webview 中单击按钮时,什么也没有发生.

However, when the button is clicked in the webview, nothing happens.

网址格式为:

https://www.xxxxxxxxxxx

我添加了以下权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" android:required="false" />

我有一个片段,它将在启用 javascript 的情况下在 onCreateView 方法(仅限代码段)中加载 webview.

I have a fragment that will load the webview in the onCreateView method (snippet only) with javascript enabled.

if(!message.isEmpty()) {            
    WebView webView = (WebView)view.findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.setWebViewClient(new WebViewClient());
    webView.loadUrl(message);
}

我创建了一个简单的 html 页面来测试:

I have created a simple html page to test:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test Android Popup</title>
</head>
<body>
<label>Test Alert 1:</label>
<button type="button" onClick="alert('Test Alert Box1');">Click Me!</button>
<br>
<label>Test Browse file</label>
<input type="file" name="img">
</body>
</html>

所以url将被加载到webview中.webview 显示一个按钮,用户可以点击该按钮来浏览他们图库中的照片.

So the url will be loaded into the webview. The webview displays a button that the user will click to browse the photos in their gallery.

网页视图如下所示:

当我点击按钮时,它们都不起作用.

None of the buttons work when I click them.

非常感谢您的任何建议,

Many thanks for any suggestions,

此代码段适用于 <4.3.但是,4.4 和 5.0 失败了.

This code snippet works for < 4.3. However, 4.4 and 5.0 it fails.

 webView.setWebChromeClient(new WebChromeClient() {
            /* Open File */
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mImageFilePath = uploadMsg;

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");

                startActivityForResult(intent, FILECHOOSER_RESULTCODE);
            }


            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                mImageFilePath = uploadMsg;

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");

                startActivityForResult(intent, FILECHOOSER_RESULTCODE);
            }

        });

推荐答案

创建此文件并将其放置在您的资产文件夹中:webdemo.html

create this file and place it in your assets folder: webdemo.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>title</title>
</head>
<body>
<h1>Web View Demo</h1>
<br>
    <input type="button" value="Say hello"
        onClick="showAndroidToast('Hello Android!')" />
    <br />
    File Uri: <label id="lbluri">no file uri</label>
    <br />
    File Path: <label id="lblpath">no file path</label>
    <br />
    <input type="button" value="Choose Photo" onClick="choosePhoto()" />
    <script type="text/javascript">
        function showAndroidToast(toast) {
            Android.showToast(toast);
        }
        function setFilePath(file) {
            document.getElementById('lblpath').innerHTML = file;
            Android.showToast(file);
        }
        function setFileUri(uri) {
            document.getElementById('lbluri').innerHTML = uri;
            Android.showToast(uri);
        }
        function choosePhoto() {
            var file = Android.choosePhoto();
            window.alert("file = " + file);
        }
    </script>
</body>
</html>

专注于此处编写的 javascript.

concentrate on the javascript written here.

将您的活动写成如下:WebViewDemo.java

public class WebViewDemo extends Activity
{

    private WebView webView;

    final int SELECT_PHOTO = 1;

    @SuppressLint("SetJavaScriptEnabled")
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_web_view);

        webView = (WebView) findViewById(R.id.webView1);

        webView.getSettings().setJavaScriptEnabled(true);

        webView.getSettings().setLoadWithOverviewMode(true);

        // Other webview settings
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setScrollbarFadingEnabled(false);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setPluginState(PluginState.ON);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setSupportZoom(true);
        webView.addJavascriptInterface(new MyJavascriptInterface(this), "Android");

        webView.loadUrl("file:///android_asset/webdemo.html");

    }

    class MyJavascriptInterface
    {

        Context mContext;

        /** Instantiate the interface and set the context */
        MyJavascriptInterface(Context c)
        {
            mContext = c;
        }

        /** Show a toast from the web page */
        @JavascriptInterface
        public void showToast(String toast)
        {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
        }

        @JavascriptInterface
        public String choosePhoto()
        {
            // TODO Auto-generated method stub
            String file = "test";
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, SELECT_PHOTO);
            return file;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        switch (requestCode)
        {
        case SELECT_PHOTO:
            if (resultCode == RESULT_OK)
            {
                Uri selectedImage = intent.getData();
                webView.loadUrl("javascript:setFileUri('" + selectedImage.toString() + "')");
                String path = getRealPathFromURI(this, selectedImage);
                webView.loadUrl("javascript:setFilePath('" + path + "')");
            }
        }

    }

    public String getRealPathFromURI(Context context, Uri contentUri)
    {
        Cursor cursor = null;
        try
        {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        finally
        {
            if (cursor != null)
            {
                cursor.close();
            }
        }
    }

}

使用此代码片段,看看它是否有效.

use this code snippet and see if it works.

以下屏幕截图来自 Android 4.4 Kitkat 设备.

我不知道这个解决方案是否对你有用.这对您来说可能只是一种解决方法或突破.我希望其中的一部分会有所帮助.

I dont know if this solution works you or not. It may be just a workaround or a breakthrough for you. I hope some part of it would help.

这篇关于使用 webview 浏览照片库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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