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 | Audio Xamarin

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):   JAVA
    MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
    mediaPlayer.start(); // no need to call prepare(); create() does that for you               

Xamarin
Any raw assets you want to be deployed with your application can be placed in
this directory (and child directories) and given a Build Action of "AndroidAsset".

These files will be deployed with your package and will be accessible using Android's
AssetManager, like this:

public class ReadAsset : Activity
{
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        InputStream input = Assets.Open ("my_asset.txt");
    }
}

Additionally, some Android functions will automatically load asset files:

Typeface tf = Typeface.CreateFromAsset (Context.Assets, "fonts/samplefont.ttf");


        public void ReproducirSonido(string sonido)
        {
            var player = new MediaPlayer();
            var fd = global::Android.App.Application.Context.Assets.OpenFd(sonido);
            player.Prepared += (s, e) =>
            {
                player.Start();
            };
            player.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
            player.Prepare();
        }

martes, 7 de enero de 2020

Error 12501 authenticating with google sign-in


<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.demilion.dontpoopyourpants">


    <application        android:supportsRtl="true"        android:allowBackup="true"        android:fullBackupContent="false"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >

        <meta-data android:name="com.google.android.gms.games.APP_ID"
            android:value="@string/app_id" />
        <meta-data android:name="com.google.android.gms.version"                   android:value="@integer/google_play_services_version"/>

        <activity            android:name="com.google.example.games.tanc.MainActivity"            android:label="@string/title_activity_main"            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Keystore file does not exist

The debug keystore file isn't in your application's directory, it's in your .android directory. If you're using Windows, it's probably in C:\Users\yourname\.android (where instead of "yourname" use your own User directory).
Once you know where it is, you can run the keytool like this:
    keytool -list -v -keystore "C:\Users\yourname\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Specify client ID settings

Next, specify your client ID settings by following the instructions specific to your platform.

Android


  1. Choose Installed application as your Application type and select Android as the installed application type (these should be your only options).
  2. In the Package name field, enter your Android application's package name.
  3. Open a terminal and run the Keytool utility to get the SHA1 fingerprint of the certificate. You should get both the release and debug certificate fingerprints.
    To get the release certificate fingerprint:
    keytool -list -keystore <path-to-production-keystore>
    
    To get the debug certificate fingerprint:
    keytool -list -keystore <path-to-debug-keystore>
    



--androiddebugkey

4. The keytool prompts you to enter a password for the keystore. The default password for the debug keystore is android. The keytool then prints the fingerprint to the terminal.

5. Paste the SHA1 fingerprint into the Signing certificate fingerprint (SHA1) field.



6. Click the Create client button, then follow the steps in the Gather credentials for authentication and authorization section below.

see on:

lunes, 6 de enero de 2020

Do Something on First App Start Only - Android Studio Tutorial

Do Something on First App Start Only


public class MainMenu extends Activity {
  


    @Override    protected void onCreate(Bundle savedInstanceState) {

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

        SharedPreferences prefs  = getSharedPreferences("prefs", MODE_PRIVATE);
        boolean firstStart = prefs.getBoolean("firstStart", true);

        if(firstStart)
        { showStartDialog();}

    }

    public void showStartDialog()
    {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(v.getContext());
        builder.setMessage("Check more apps!!!")
                .setCancelable(false)
                .setPositiveButton("OK GO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/developer?id=Demilion") ) );
                    }
                })
                .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        builder.create()
                .show();

        SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("fistStart", false);
        editor.apply();
    }





https://www.youtube.com/watch?v=2I1n6A6JJzw

miércoles, 1 de enero de 2020

Passing Data To Other Activity Using Intent.

  1. Create a New Explicit or Implicit Intent object in source activity.
  2. Call intent.putExtra(String key, Object data) method to save data in it.
  3. Call startActivity(intent) method in source activity to pass the intent to android os.
  4. Call getIntent() method in target activity.
  5. Use intent.getStringExtra(String key) to get the transferred data.
This-

Intent intent = new Intent(this, BasicViewsActivity.class);
intent.putExtra("amountTime", String.valueOf(amountTime));
startActivity(intent);

BasicViewActivity-

Intent intent = getIntent();
String amountTime =   intent.getStringExtra("amountTime");


https://www.dev2qa.com/passing-data-between-activities-android-tutorial/