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

miércoles, 28 de octubre de 2020

Don't navigate to other pages in WebView (shouldOverrideUrlLoading )

 ref: https://stackoverflow.com/questions/19426742/dont-navigate-to-other-pages-in-webview-disable-links-and-references


WebView gives developers an easy way to embed a web-based application to an Android app with almost no code. Just give it some URL and it works.

Implementation of the application which displays the predefined web page in a WebView is relatively straightforward.

        myWebView.loadUrl("your_pages");

There are two scenarios how a web app might react to a user click event. The first one is redirection. WebView client has quite an easy way to listen for redirects. You just need to override its method shouldOverrideUrlLoading() .

package com.demilion.myapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import java.io.IOException;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.webkit.WebViewClient;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;

public class MainActivity extends Activity {
private AdView mAdView;
private boolean loaded = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

MobileAds.initialize(this,
"ca-app-pub-000000000000000~0000000000");

mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);

WebView myWebView = (WebView) this.findViewById(R.id.webView);
myWebView.setWebChromeClient(new WebChromeClient());

myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");

myWebView.addJavascriptInterface(new AudioInterface(this), "AndAud");

// Enable JavaScript
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);


//myWebView.loadUrl("https://codepen.io/loktar00/pen/CHpGo/");
//myWebView.loadUrl("file:///android_asset/myhtml.html");
myWebView.loadUrl("https://codepen.io/loktar00/pen/CHpGo/");



myWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

if(loaded == false){
view.loadUrl(url);
loaded = true;
return true;
}else{
return false;
}

}
})
;







}

public class WebAppInterface {

Context
context;

/**
* Instantiate the interface and set the context
*
* @param context
*/
public WebAppInterface(Context context) {
this.context = context;
}

/**
* Show a dialog from the web page.
*
* @param message
* message of the dialog
*/
@JavascriptInterface
public void showDialog(String message) {

// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
builder.setMessage(message).setNeutralButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss()
;
}
})
;
// Create the AlertDialog object and return it
builder.create().show();
}
}

public class AudioInterface {
Context
mContext;

AudioInterface(Context c) {
mContext = c;
}

//Play an audio file from the webpage
@JavascriptInterface
public void playAudio(String aud) { //String aud - file name passed
//from the JavaScript function
final MediaPlayer mp;

try {
AssetFileDescriptor fileDescriptor =
mContext.getAssets().openFd(aud);
mp = new MediaPlayer();
mp.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(),
fileDescriptor.getLength());
fileDescriptor.close();
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}


viernes, 5 de junio de 2020

Audio android java

A continuación, se muestra un ejemplo de cómo reproducir un archivo de audio que está disponible como recurso local sin procesar (guardado en el directorio res/raw/ de tu app):
    MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
    mediaPlayer.start(); // no need to call prepare(); create() does that for you