sábado, 28 de noviembre de 2020

¿Cómo acceder a la cámara con WebView Android?

main.java

 private WebView wv;

//Definir campos

private static final int FILECHOOSER_RESULCODE =1;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mUploadMessages;
private Uri mCapturedImageUri = null;
//Fin
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar().hide();// Oculta la cabecera.
    wv = (WebView) findViewById(R.id.wv);
    wv.loadUrl("https://Mobile.xhtml");
    wv.setWebViewClient(new MyClient());
    wv.setWebChromeClient(new GoogleClient());
    WebSettings webSettings = wv.getSettings();
    webSettings.setJavaScriptEnabled(true);
    wv.getSettings().setDomStorageEnabled(true);
    wv.getSettings().setAllowFileAccess(true);
    wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    wv.clearCache(false);

    wv.setWebChromeClient(new WebChromeClient(){
        //Implementacion de Canvas de archivos
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String accepType){
            mUploadMessage = uploadMsg;
            openImageChooser();
        }
        public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams filechooserParams){
            mUploadMessages = filePathCallback;
            openImageChooser();
            return true;
        }
        public void openFileChooser(ValueCallback<Uri> uploadMsg){
            openFileChooser(uploadMsg, "");
        }
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
            openFileChooser(uploadMsg, acceptType);
        }
        //Fin
    });
    //Metodo para descargar pdf
    wv.setDownloadListener(new DownloadListener()
    {
        @Override
        public void onDownloadStart(String url, String userAgent,String contentDisposition, String mimeType,long contentLength) {
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setMimeType(mimeType);
            String cookies = CookieManager.getInstance().getCookie(url);
            request.addRequestHeader("cookie", cookies);
            request.addRequestHeader("User-Agent", userAgent);
            request.setDescription("Descargando pdf..."); //request.setDescription("Downloading file...");
            request.setTitle(URLUtil.guessFileName(url, contentDisposition,mimeType));
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalFilesDir(MainActivity.this,Environment.DIRECTORY_DOWNLOADS,".pdf");
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);
            Toast.makeText(getApplicationContext(), "Descargando pdf...",Toast.LENGTH_LONG).show();
        }});
    wv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            wv.loadUrl("TU WEB ");
        }
    });
}
//metodo para abrir google drive
private void openImageChooser(){
    try{
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "FolderName");
        if (!imageStorageDir.exists()){
            imageStorageDir.mkdirs();
        }
        File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        mCapturedImageUri = Uri.fromFile(file);
        final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageUri);
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
        startActivityForResult(chooserIntent, FILECHOOSER_RESULCODE);
    } catch (Exception e){
        e.printStackTrace();
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    super.onActivityResult(requestCode, resultCode, intent);
    if (requestCode==FILECHOOSER_RESULCODE){
        if (null == mUploadMessage && null == mUploadMessages){
            return;
        }
        if (null != mUploadMessage){
            handleUploadMessage(requestCode, resultCode, intent);
        } else if (mUploadMessages != null){
            handleUploadMessages(requestCode, resultCode, intent);
        }
    }
}

private void handleUploadMessage(int requestCode, int resultCode, Intent intent) {
    Uri result = null;
    try {
        if (resultCode != RESULT_OK){
            result = null;
        } else {
            result = intent == null ? mCapturedImageUri : intent.getData();
        }
    } catch (Exception e){
        e.printStackTrace();
    }
    mUploadMessage.onReceiveValue(result);
    mUploadMessage = null;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void handleUploadMessages(int requestCode, int resultCode, Intent intent) {
    Uri[] results = null;
    try {
        if (resultCode != RESULT_OK){
            results = null;
        } else {
            if (intent != null){
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null){
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++){
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null){
                    results = new Uri[]{Uri.parse(dataString)};
                }
            } else {
                results = new Uri[]{mCapturedImageUri};
            }
        }
    } catch (Exception e){
        e.printStackTrace();
    }
    mUploadMessages.onReceiveValue(results);
    mUploadMessages = null;
}
class MyClient extends WebViewClient
{
    @Override
    public void onPageStarted(WebView view,String url,Bitmap favicon){
        super.onPageStarted(view,url,favicon);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view,String Url)
    {
        view.loadUrl(Url);
        return true;
    }
    @Override
    public void onPageFinished(WebView view,String url)
    {
        super.onPageFinished(view,url);
    }
}
class GoogleClient extends WebChromeClient
{
    @Override
    public void onProgressChanged(WebView view,int newProgress)
    {
        super.onProgressChanged(view,newProgress);
    }
}

@Override
public void onBackPressed() {
    if (wv.canGoBack())
        wv.goBack();
    else
        super.onBackPressed();

}





Esto fue robado de: https://es.stackoverflow.com/questions/106689/c%C3%B3mo-acceder-a-la-c%C3%A1mara-con-webview-android

No hay comentarios:

Publicar un comentario