使用相机和GPS的Android WebView



我正在Android浏览器中使用WebView,但想知道是否有人将浏览器与html5一起使用来使用本地设备的相机和gps?或者我需要为此与Java源代码建立Javascript连接吗?

这在 IOS 中也有效吗?

这是,不使用PhoneGap。

最好Henrik

可能有点晚了,但以防万一,我会给你一个例子来做到这一点。(相机)

1//

//将其添加到您的网络Chrome客户端

myWebView.setWebChromeClient(new WebChromeClient() 
{
    public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) 
    { 
        mUploadMessage = uploadMsg;
        Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
        Calendar cal = Calendar.getInstance();
        cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
        File photo = new File(Environment.getExternalStorageDirectory(), sdf.format(cal.getTime()) +".jpg");
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
        picUri = Uri.fromFile(photo);
        startActivityForResult(cameraIntent, TAKE_PICTURE);                 
    }
}); 

2///添加此函数

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    switch(requestCode)
    {
        case TAKE_PICTURE:
            if(resultCode == Activity.RESULT_OK)
            {
                Uri mypic = picUri;
                mUploadMessage.onReceiveValue(mypic);
                mUploadMessage = null;
            }
            else
            {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
                return;
            }
        default:
        {
            return;
        }   
    }
}   

3//HTML 看起来像这样

<input type="file" id="files" name="files"  accept="image/*" capture="camera" >

上面的代码将打开本机相机应用程序。

附言这是来自不同来源的代码的混合。

值得指出的是,这里显示的代码应该在哪里,因为它对于新手来说并不明显 - 它在你的活动类中,即

public class MyActivity extends Activity {
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        ...
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        myWebView.setWebChromeClient(new WebChromeClient()
        {
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {  
                ...
            }
        });
    }
}

就我而言,我已经覆盖了 makeWebViewEngine 方法,以便能够修改转换为SystemWebViewEngineCordovaWebViewEngine,如下所示(基于此答案):

public class MainActivity extends CordovaActivity {
    private static final int FILECHOOSER_RESULTCODE = 12345;
    private ValueCallback<Uri> mUploadMessage;
    private Uri mPicUri;
    private ValueCallback<Uri[]> mFilePathCallback;
    private String mCameraPhotoPath;
    @Override
    protected CordovaWebViewEngine makeWebViewEngine() {
        SystemWebViewEngine systemWebViewEngine = (SystemWebViewEngine) super.makeWebViewEngine();
        SystemWebView systemWebView = (SystemWebView) systemWebViewEngine.getView();
        systemWebView.setWebChromeClient(new SystemWebChromeClient(systemWebViewEngine) {
            // For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
                Calendar cal = Calendar.getInstance();
                cal.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
                File photo = new File(Environment.getExternalStorageDirectory(), sdf.format(cal.getTime()) + ".jpg");
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
                mPicUri = Uri.fromFile(photo);
                startActivityForResult(cameraIntent, FILECHOOSER_RESULTCODE);
            }
            // For Android 5.0+
            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    WebChromeClient.FileChooserParams fileChooserParams) {
                // Double check that we don't have any existing callbacks
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = filePathCallback;
                // Set up the take picture intent
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                    // Create the File where the photo should go
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                    } catch (IOException ex) {
                        // Error occurred while creating the File
                        Log.e(TAG, "Unable to create Image File", ex);
                    }
                    // Continue only if the File was successfully created
                    if (photoFile != null) {
                        mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(photoFile));
                    } else {
                        takePictureIntent = null;
                    }
                }
                // Set up the intent to get an existing image
                Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("image/*");
                // Set up the intents for the Intent chooser
                Intent[] intentArray;
                if (takePictureIntent != null) {
                    intentArray = new Intent[]{takePictureIntent};
                } else {
                    intentArray = new Intent[0];
                }
                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                startActivityForResult(chooserIntent, MainActivity.FILECHOOSER_RESULTCODE);
                return true;
            }
        });
        return systemWebViewEngine;
    }
    // …
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);
    }
}

此外,基于另一个答案,我必须为 Android 4.1 指定openFileChooser方法,对于 Android 5.0+,我必须指定onShowFileChooser方法。

顺便说一下,我修改了onActivityResult方法,如下所示:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (Build.VERSION.SDK_INT >= 21) {
            if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
                super.onActivityResult(requestCode, resultCode, intent);
                return;
            }
            Uri[] results = null;
            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                String dataString = intent.getDataString();
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                } else {
                    // If there is not data, then we may have taken a photo
                    if (mCameraPhotoPath != null) {
                        results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }
                }
            }
            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
        } else {
            if (requestCode == FILECHOOSER_RESULTCODE) {
                if (null == this.mUploadMessage) {
                    return;
                }
                Uri result;
                if (resultCode != RESULT_OK) {
                    result = null;
                } else {
                    result = intent == null ? this.mPicUri : intent.getData(); // retrieve from the private variable if the intent is null
                }
                this.mUploadMessage.onReceiveValue(result);
                this.mUploadMessage = null;
            }
        }
    }

感谢@Will和@Christian在这个答案中指出了好的方向,顺便说一句:)

最新更新