jueves, 8 de diciembre de 2022

MainActivity.java - Tu estilo v1.1 - Código Java - Android Studio - WebView

package com.estilopropiomx.tienda;

import static android.content.ContentValues.TAG;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.webkit.WebViewCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.RenderProcessGoneDetail;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
String id;
TextView mitext;
TextView miurl2;
private float m_downX;
public String url1;
private String mCM;
private ValueCallback mUM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;
private static final int PERMISO_WRITE_EXTERNAL = 0;
private WebView webView;
private WebChromeClient.CustomViewCallback customViewCallback;
private FrameLayout customViewContainer;
private View mCustomView;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
if(Build.VERSION.SDK_INT >= 21){
Uri[] results = null;
//Check if response is positive
if(resultCode== Activity.RESULT_OK){
if(requestCode == FCR){
if(null == mUMA){
return;
}
if(intent == null || intent.getData() == null){
//Capture Photo if no image available
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = intent.getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
}else{
if(requestCode == FCR){
if(null == mUM) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1) {
mUM.onReceiveValue(result);
}
mUM = null;
}
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_Tienda_NoActionBar);
super.onCreate(savedInstanceState);
//----------pantalla completa--------------------------
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN
);
//-----------------------------------------------------
setContentView(R.layout.activity_main);
ComprobarPermisos();
customViewContainer = findViewById(R.id.customViewContainer);
webView = findViewById(R.id.webview);
SwipeRefreshLayout refresh = findViewById(R.id.swipeR);
ImageButton casabutton = findViewById(R.id.casabutton);
ImageButton micuentabutton = findViewById(R.id.micuentabutton);
ImageButton tiendabutton = findViewById(R.id.tiendabutton);
ImageButton compartirbutton = findViewById(R.id.compartirbutton);
ImageButton limpiarcache = findViewById(R.id.limpiarcachebutton);
ImageButton masbutton = findViewById(R.id.masopcionesbutton);
ImageButton browserbutton = findViewById(R.id.otronavegadorbutton);
ImageButton blogbutton = findViewById(R.id.blogbutton);
ImageButton subastabutton = findViewById(R.id.subastabutton);
ImageButton deseosbutton =findViewById(R.id.deseosbutton);
ImageButton carritobutton = findViewById(R.id.cartbutton);
ImageButton atrasbtn = findViewById(R.id.atrasbtn);
ImageButton adelantebtn = findViewById(R.id.adelantebutn);
ImageButton listadetiendasbtn = findViewById(R.id.store_listingbtn);
ImageButton categoriasdeproductos = findViewById(R.id.categoriasbt);
ImageButton afiliadosbtn = findViewById(R.id.affiliatebtn);
ImageButton vendorbtn = findViewById(R.id.vendordashboardbtn);
ImageButton colaboradorbtn = findViewById(R.id.colaboradordashboardbtn);
HorizontalScrollView scroll = findViewById(R.id.horizontalscrollview);
String mydata;
String nuevoid;
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
SharedPreferences myprefer;
SharedPreferences myurl1;
mitext = findViewById(R.id.textView3);
miurl2 = findViewById(R.id.textViewurl);
myprefer = getSharedPreferences("miid", Context.MODE_PRIVATE);
myurl1 = getSharedPreferences("url", Context.MODE_PRIVATE);
mitext.setText(myprefer.getString("id", ""));
miurl2.setText(myurl1.getString("url", "https://tienda.estilopropiomx.com"));
Bundle extra = this.getIntent().getExtras();
String nuevaurl;
nuevaurl = miurl2.getText().toString();
url1 = "https://tienda.estilopropiomx.com";
refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
webView.clearCache(true);
webView.reload();
}
});
WebSettings webSettings = webView.getSettings();
webSettings.setAppCacheMaxSize(100*1024*1024);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setJavaScriptEnabled(true);
//--------------Zoom--------------------------
webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);
webView.getSettings().setDisplayZoomControls(false);
//--------------UPLOAD FILES-------------------
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
//-------------------------------------------
//-----------acepta http--------------------
String commont_agent = "Chrome/56.0.0 Mobile";
webSettings.setUserAgentString(commont_agent);
//-------------------------------------------
PackageInfo webViewPackageInfo = WebViewCompat.getCurrentWebViewPackage(getApplicationContext());
Log.d("MY_APP_TAG", "WebView version: "+webViewPackageInfo.versionName);
if (appLinkData != null){
String dat = String.valueOf(appLinkData);
if(dat.startsWith("http")){
webView.loadUrl(dat);
}else {
Toast.makeText(getApplicationContext(), "El texto: "+dat+" No es una URL, se cargará la ultima url cargada", Toast.LENGTH_LONG).show();
webView.loadUrl(nuevaurl);
}
}else if(extra != null) {
String nuevadata;
nuevadata = getIntent().getStringExtra(Intent.EXTRA_TEXT);
mydata = getIntent().getStringExtra("url");
nuevoid = getIntent().getStringExtra("id");
if(nuevadata != null){
if(nuevadata.startsWith("http")){
webView.loadUrl(nuevadata);
}else{
Toast.makeText(getApplicationContext(), "No puedes navegar a: "+nuevadata, Toast.LENGTH_LONG).show();
}
}
if(mydata != null){
if(mydata.startsWith("http")){
webView.loadUrl(mydata);
}
}
if(nuevoid != null){
if (nuevoid != ""){
SharedPreferences.Editor myeditor = myprefer.edit();
myeditor.putString("id", nuevoid);
myeditor.commit();
Toast.makeText(getApplicationContext(), "Tu ID de afiliado a cambiado a: " +mitext.getText().toString(), Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Tu ID de afiliado esta desactivado", Toast.LENGTH_LONG).show();
}
}
}else {
webView.loadUrl(nuevaurl);
}

atrasbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.goBack();
refresh.setRefreshing(true);
if(webView.canGoBack()){
webView.canGoBack();
}else{
refresh.setRefreshing(false);
Toast.makeText(getApplicationContext(), "No puedes ir atras, no hay nada", Toast.LENGTH_LONG).show();
}
}
});
adelantebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.goForward();
refresh.setRefreshing(true);
if(webView.canGoForward()){
webView.canGoForward();
}else{
refresh.setRefreshing(false);
Toast.makeText(getApplicationContext(), "No puedes ir hacia adelante porque no hay nada adelante", Toast.LENGTH_LONG).show();
}
}
});
casabutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/");
refresh.setRefreshing(true);
}
});
afiliadosbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/affiliate-dashboard");
refresh.setRefreshing(true);
}
});
vendorbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/dashboard");
refresh.setRefreshing(true);
}
});
colaboradorbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/escritorio-de-colaborador");
refresh.setRefreshing(true);
}
});
micuentabutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/mi-cuenta");
refresh.setRefreshing(true);
}
});
blogbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/blog");
refresh.setRefreshing(true);
}
});
tiendabutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/tienda");
refresh.setRefreshing(true);
}
});
listadetiendasbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/store-listing");
refresh.setRefreshing(true);
}
});
subastabutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/subastas");
refresh.setRefreshing(true);
}
});
categoriasdeproductos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/categorias-de-productos");
refresh.setRefreshing(true);
}
});
deseosbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/lista-de-deseos");
refresh.setRefreshing(true);
}
});
carritobutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.loadUrl("https://tienda.estilopropiomx.com/cart");
refresh.setRefreshing(true);
}
});
compartirbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
compartirenlace();

}
});
limpiarcache.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
webView.clearCache(true);
webView.clearHistory();
Toast.makeText(getApplicationContext(), "Tu Cache se ha borrado", Toast.LENGTH_LONG).show();
}
});
masbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
abriractivity();
}
});
browserbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
}
});
id = mitext.getText().toString();
if(isOnline(getApplicationContext())){
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}else {
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
}
//handle downloading
webView.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 archivo");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Descargando archivo", Toast.LENGTH_LONG).show();
}});
//---------------------------------------------------------------------------------------
webView.setWebChromeClient(new WebChromeClient(){
//For Android 5.0+
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
FileChooserParams fileChooserParams){
if(mUMA != null){
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(TAG, "La creación del archivo falló", ex);
}
if(photoFile != null){
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
}else{
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
// En la siguiente linea especificamos el tipo de archivos que permitimos subir desde la aplicación.
contentSelectionIntent.setType("*/*");
// Si deseamos permitir subir otro archivos, por ejemplo PDF, modificaremos la linea y la dejaremos de la siguiente manera:
// contentSelectionIntent.setType("application/pdf, image/*");
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, "Selección de Archivo");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
private Bitmap mDefaultVideoPoster;
private View mVideoProgressView;
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
if(mCustomView == null){
callback.onCustomViewHidden();
return;
}
mCustomView = view;
scroll.setVisibility(View.GONE);
webView.setVisibility(View.GONE);
customViewContainer.setVisibility(View.VISIBLE);
customViewContainer.addView(view);
customViewCallback = callback;
}
@Override
public void onHideCustomView() {
super.onHideCustomView();
if(mCustomView == null){
return;
}
scroll.setVisibility(View.VISIBLE);
webView.setVisibility(View.VISIBLE);
customViewContainer.setVisibility(View.GONE);
mCustomView.setVisibility(View.GONE);
customViewContainer.removeView(mCustomView);
customViewCallback.onCustomViewHidden();
mCustomView = null;
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
refresh.setRefreshing(true);
url1 = url;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url1) {
if (url1.startsWith("http")) {
refresh.setRefreshing(true);
return false;
}
if (url1.startsWith("https")) {
refresh.setRefreshing(true);
return false;
}
if (url1.startsWith("facebook")) {
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
return false;
}
if (url1.startsWith("youtube")) {
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
return false;
}
if (url1.startsWith("tiktok")) {
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
return false;
}
if (url1.startsWith("whatsapp")) {
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
return false;
}
if (url1.startsWith("pinterest")) {
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
return false;
}
if (url1.startsWith("play")) {
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
return false;
}
if (url1.startsWith("maps")) {
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
return false;
}
if (url1.startsWith("twetter")) {
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
return false;
}
if (url1.startsWith("mailto")) {
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
return false;
}
return true;
}
public void download(WebView view, String url) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setMimeType("*/*");
String cookie = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("Cookie", cookie);
//request.addRequestHeader("User-Agent", userAgent);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(true);
request.setDescription("Downloading File...");
request.setTitle("Archivo");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "archivo");
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
refresh.setRefreshing(false);
url1 = url;
SharedPreferences.Editor myeditor2 = myurl1.edit();
myeditor2.putString("url", url);
myeditor2.commit();
}
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
if(errorResponse != null){
}
super.onReceivedHttpError(view, request, errorResponse);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
invalidateOptionsMenu();
}
});
webView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getPointerCount() > 1) {
//Multi touch detected
return true;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
// guardar la x
m_downX = event.getX();
}
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
// Establecer x para que no se mueva
event.setLocation(m_downX, event.getY());
}
break;
}
return false;
}
});
}
@RequiresApi(api = Build.VERSION_CODES.M)
public static boolean isOnline(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null){
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
Toast.makeText(context, "Tenemos conexión de Datos Mobiles", Toast.LENGTH_LONG).show();
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
Toast.makeText(context, "Tenemos conexión WiFi", Toast.LENGTH_LONG).show();
return true;
} else {
Toast.makeText(context, "No existe conexión a Internet", Toast.LENGTH_LONG).show();
}
}
}
return false;
}
// Create an image file
@RequiresApi(api = Build.VERSION_CODES.FROYO)
private File createImageFile() throws IOException{
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
@SuppressLint({"NewApi", "LocalSuppress"}) File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
//@Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; }
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
WebView webview = findViewById(R.id.webview);
WebSettings webSettings = webview.getSettings();
if(item.getItemId() == R.id.homemenu){
webview.loadUrl("https://tienda.estilopropiomx.com");
}
if(item.getItemId() == R.id.sinanunciosmenu){
webview.loadUrl("https://tienda.estilopropiomx.com/mi-cuenta");
}
if(item.getItemId() == R.id.conanunciosmenu){
webview.loadUrl("https://tienda.estilopropiomx.com/tienda");

}
if(item.getItemId() == R.id.limpiarcachemenu){
webview.clearCache(true);
webview.clearHistory();
}
if(item.getItemId() == R.id.compartirmenu){
compartirenlace();
}
if(item.getItemId() == R.id.conectarcongooglemenu){
webview.loadUrl("https://myaccount.google.com");
}
if(item.getItemId() == R.id.masopciones){
abriractivity();
}
return super.onOptionsItemSelected(item);
}
public void abriractivity(){
Intent in = new Intent(MainActivity.this, ConfiguracionesActivity.class);
startActivity(in);
}
public void compartirenlace(){
String nuevoid = mitext.getText().toString();
String miurl;
String afiliado = "?ref="+nuevoid;
if(nuevoid == ""){
miurl = url1;
}else if (url1.startsWith("https://tienda.estilopropiomx.com")){
miurl = url1+afiliado;
Toast.makeText(getApplicationContext(), "Link activo +"+afiliado, Toast.LENGTH_LONG).show();
}else{
miurl = url1;
Toast.makeText(getApplicationContext(), "Tu link de afiliado no aparecerá porque no es un enlace con estilo", Toast.LENGTH_LONG).show();
}

Intent send = new Intent();
send.setAction(Intent.ACTION_SEND);
send.putExtra(Intent.EXTRA_TEXT, miurl);
send.setType("text/plain");

Intent sharesend = Intent.createChooser(send, null);
startActivity(sharesend);
}
private void comprobarUrlWithdraw(){
if (webView.getUrl() == "https://tienda.estilopropiomx.com/dashboard/withdraw/"){
Toast.makeText(getApplicationContext(), "Para retirar ganancias abre esta página en otro navegador", Toast.LENGTH_LONG).show();
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
}
}
private void ComprobarPermisos() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
} else {
// No se tiene el permiso, es necesario pedirlo al usuario
PedirPermiso();
}
}

private void PedirPermiso() {
//Comprobación 'Racional'
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

//Mostramos un AlertDialog al usuario explicándole la necesidad del permiso
AlertDialog AD;
AlertDialog.Builder ADBuilder = new AlertDialog.Builder(MainActivity.this);
ADBuilder.setMessage("Para navegar con estilo permitenos guardar archivos. Esto es en caso de que necesites descargar archivos. Sin este permiso no podremos continuar.");
ADBuilder.setPositiveButton("Continuar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

/*Cuando el usuario pulse sobre el botón del AlertDialog se procede a solicitar
el permiso con el siguiente código:*/

ActivityCompat.requestPermissions(
MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISO_WRITE_EXTERNAL);
}
});

//Mostramos el AlertDialog
AD = ADBuilder.create();
AD.show();

} else {
/*Si no hay necesidad de una explicación racional, pasamos a solicitar el
permiso directamente*/
ActivityCompat.requestPermissions(
MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISO_WRITE_EXTERNAL);
}


}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISO_WRITE_EXTERNAL) {
/* Resultado de la solicitud para permiso de cámara
Si la solicitud es cancelada por el usuario, el método .lenght sobre el array
'grantResults' devolverá null.*/

if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// Permiso concedido
Toast.makeText(getApplicationContext(), "Permiso Concedido", Toast.LENGTH_SHORT).show();

} else {
/* Permiso no concedido
Aquí habría que explicar al usuario el por qué de este permiso
y volver a solicitarlo .*/
//
PedirPermiso();
}
}
}
public boolean inCustomView(){
return (mCustomView != null);
}
public void hideCustomView(){
WebChromeClient mWebCromeClient = new WebChromeClient();
mWebCromeClient.onHideCustomView();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
WebView myWebView = findViewById(R.id.webview);
if(inCustomView()){
hideCustomView();
return true;
}
if(myWebView.canGoBack()){
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
public class MyRendererTrackingWebViewClient extends WebViewClient {
private WebView mWebView;
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public boolean onRenderProcessGone(WebView view,
RenderProcessGoneDetail detail) {
if (!detail.didCrash()) {
// Renderer was killed because the system ran out of memory.
// The app can recover gracefully by creating a new WebView instance
// in the foreground.
Log.e("MY_APP_TAG", "System killed the WebView rendering process " +
"to reclaim memory. Recreating...");
if (mWebView != null) {
ViewGroup webViewContainer =
(ViewGroup) findViewById(R.id.webview);
webViewContainer.removeView(mWebView);
mWebView.destroy();
mWebView = null;
}
// By this point, the instance variable "mWebView" is guaranteed
// to be null, so it's safe to reinitialize it.
return true; // The app continues executing.
}
// Renderer crashed because of an internal error, such as a memory
// access violation.
Log.e("MY_APP_TAG", "The WebView rendering process crashed!");
// In this example, the app itself crashes after detecting that the
// renderer crashed. If you choose to handle the crash more gracefully
// and allow your app to continue executing, you should 1) destroy the
// current WebView instance, 2) specify logic for how the app can
// continue executing, and 3) return "true" instead.
return false;
}
}

}
Share:

0 comments:

Publicar un comentario