jueves, 8 de diciembre de 2022

BuscadorActivity.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.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
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.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.FrameLayout;
import android.widget.SearchView;
import android.widget.Toast;

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

public class BuscadorActivity extends AppCompatActivity {
private float m_downX;
public String url1;
private String mCM;
private ValueCallback mUM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;
private WebView webView;
private WebChromeClient.CustomViewCallback customViewCallback2;
private FrameLayout customViewContainer2;
private View mCustomView2;
@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;
}
}
}

String Base_Url = "https://google.com";
String Search_path = "/search?q=";
@RequiresApi(api = Build.VERSION_CODES.M)
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN
);
setContentView(R.layout.activity_buscador);
customViewContainer2 = findViewById(R.id.customViewContainer);
SearchView mySearch = findViewById(R.id.searchView);
webView = findViewById(R.id.webview);
SwipeRefreshLayout refresh = findViewById(R.id.swipeR);
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);
String commont_agent = "Chrome/56.0.0 Mobile";
webSettings.setUserAgentString(commont_agent);
Bundle extra = this.getIntent().getExtras();
String mydata;
if(extra != null) {
mydata = getIntent().getStringExtra("url");
if(mydata.startsWith("http")){
webView.loadUrl(mydata);
}else{
webView.loadUrl("https://tienda.estilopropiomx.com");
}
}else{
webView.loadUrl("https://tienda.estilopropiomx.com");
}
if(isOnline(getApplicationContext())){
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}else {
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
}
//--------------UPLOAD FILES-------------------
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
//-------------------------------------------

//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(BuscadorActivity.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(mCustomView2 == null){
callback.onCustomViewHidden();
return;
}
mCustomView2 = view;
webView.setVisibility(View.GONE);
customViewContainer2.setVisibility(View.VISIBLE);
customViewContainer2.addView(view);
customViewCallback2 = callback;
}
@Override
public void onHideCustomView() {
super.onHideCustomView();
if(mCustomView2 == null){
return;
}
webView.setVisibility(View.VISIBLE);
customViewContainer2.setVisibility(View.GONE);
mCustomView2.setVisibility(View.GONE);
customViewContainer2.removeView(mCustomView2);
customViewCallback2.onCustomViewHidden();
mCustomView2 = 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;
mySearch.setQuery(url1, false);
}
@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;
mySearch.setQuery(url1, false);
}
@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;
}
});
mySearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
if(query != null){
if (query.startsWith("https://tienda.estilopropiomx.com")){
Intent send = new Intent(BuscadorActivity.this, MainActivity.class);
send.putExtra("url", query);
startActivity(send);
}
if(query.startsWith("http://")){
webView.loadUrl(query);
return true;
}
if(query.startsWith("https://")){
webView.loadUrl(query);
return true;
}
else{
webView.loadUrl(Base_Url+Search_path+query);
return true;
}
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
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)) {
return true;
} else {
}
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else {
}
}
}
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.menubuscar, 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.homemenu1){
Intent send = new Intent(BuscadorActivity.this, MainActivity.class);
send.putExtra("url", "https://tienda.estilopropiomx.com");
startActivity(send);
}
if(item.getItemId() == R.id.limpiarcachemenu1){
webview.clearCache(true);
webview.clearHistory();
}
if(item.getItemId() == R.id.compartirmenu1){
compartirenlace();
}
if(item.getItemId() == R.id.conectarcongooglemenu1){
Intent intent = (new Intent(Intent.ACTION_VIEW, Uri.parse(url1)));
startActivity(intent);
}
if(item.getItemId() == R.id.masopciones1){
abriractivity();
}
if(item.getItemId() == R.id.regresar){
Intent in = new Intent(BuscadorActivity.this, MainActivity.class);
startActivity(in);
}
return super.onOptionsItemSelected(item);
}
public void abriractivity(){
Intent in = new Intent(BuscadorActivity.this, ConfiguracionesActivity.class);
startActivity(in);
}
public void compartirenlace(){
String miurl = url1;
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);
}
public boolean inCustomView(){
return (mCustomView2 != 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;
}
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