bigboy6762

Webview Java

Nov 29th, 2021 (edited)
533
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 47.84 KB | None | 0 0
  1. import android.Manifest;
  2. import android.annotation.SuppressLint;
  3. import android.annotation.TargetApi;
  4. import android.app.Activity;
  5. import android.app.ActivityManager;
  6. import android.app.AlertDialog;
  7. import android.app.DownloadManager;
  8. import android.app.Notification;
  9. import android.app.NotificationChannel;
  10. import android.app.NotificationManager;
  11. import android.app.PendingIntent;
  12. import android.app.SearchManager;
  13. import android.content.ActivityNotFoundException;
  14. import android.content.ClipData;
  15. import android.content.Context;
  16. import android.content.DialogInterface;
  17. import android.content.Intent;
  18. import android.content.pm.PackageManager;
  19. import android.content.res.Configuration;
  20. import android.graphics.Bitmap;
  21. import android.graphics.BitmapFactory;
  22. import android.graphics.Color;
  23. import android.media.RingtoneManager;
  24. import android.net.Uri;
  25. import android.net.http.SslError;
  26. import android.os.Build;
  27. import android.os.Bundle;
  28. import android.os.Environment;
  29. import android.os.Handler;
  30. import android.print.PrintAttributes;
  31. import android.print.PrintDocumentAdapter;
  32. import android.print.PrintJob;
  33. import android.print.PrintManager;
  34. import android.provider.MediaStore;
  35. import android.provider.Settings;
  36. import android.util.Log;
  37. import android.view.KeyEvent;
  38. import android.view.Menu;
  39. import android.view.MenuItem;
  40. import android.view.View;
  41. import android.view.ViewTreeObserver;
  42. import android.view.WindowManager;
  43. import android.webkit.CookieManager;
  44. import android.webkit.DownloadListener;
  45. import android.webkit.GeolocationPermissions;
  46. import android.webkit.ServiceWorkerClient;
  47. import android.webkit.ServiceWorkerController;
  48. import android.webkit.SslErrorHandler;
  49. import android.webkit.URLUtil;
  50. import android.webkit.ValueCallback;
  51. import android.webkit.WebChromeClient;
  52. import android.webkit.WebResourceRequest;
  53. import android.webkit.WebResourceResponse;
  54. import android.webkit.WebSettings;
  55. import android.webkit.WebView;
  56. import android.webkit.WebViewClient;
  57. import android.widget.ProgressBar;
  58. import android.widget.TextView;
  59. import android.widget.Toast;
  60.  
  61. import androidx.annotation.NonNull;
  62. import androidx.annotation.Nullable;
  63. import androidx.appcompat.app.ActionBarDrawerToggle;
  64. import androidx.appcompat.app.AppCompatActivity;
  65. import androidx.appcompat.widget.SearchView;
  66. import androidx.appcompat.widget.Toolbar;
  67. import androidx.browser.customtabs.CustomTabsIntent;
  68. import androidx.core.app.ActivityCompat;
  69. import androidx.core.app.NotificationCompat;
  70. import androidx.core.content.ContextCompat;
  71. import androidx.core.view.GravityCompat;
  72. import androidx.drawerlayout.widget.DrawerLayout;
  73. import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
  74.  
  75. import com.google.android.gms.ads.AdRequest;
  76. import com.google.android.gms.ads.AdView;
  77. import com.google.android.gms.ads.MobileAds;
  78. import com.google.android.gms.ads.initialization.InitializationStatus;
  79. import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
  80. import com.google.android.material.navigation.NavigationView;
  81. import com.google.firebase.BuildConfig;
  82. //import com.google.firebase.messaging.FirebaseMessagingService;
  83. import com.google.firebase.iid.FirebaseInstanceId;
  84. //import com.google.zxing.integration.android.IntentIntegrator;
  85. //import com.google.zxing.integration.android.IntentResult;
  86.  
  87. import java.io.ByteArrayOutputStream;
  88. import java.io.File;
  89. import java.io.IOException;
  90. import java.math.BigInteger;
  91. import java.security.SecureRandom;
  92. import java.text.SimpleDateFormat;
  93. import java.util.Date;
  94. import java.util.Objects;
  95. import java.util.regex.Matcher;
  96. import java.util.regex.Pattern;
  97.  
  98. public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
  99.  
  100.     // permission variables
  101.     static boolean ASWP_JSCRIPT             = SmartWebView.ASWP_JSCRIPT;
  102.     static boolean ASWP_FUPLOAD             = SmartWebView.ASWP_FUPLOAD;
  103.     static boolean ASWP_CAMUPLOAD           = SmartWebView.ASWP_CAMUPLOAD;
  104.     static boolean ASWP_ONLYCAM             = SmartWebView.ASWP_ONLYCAM;
  105.     static boolean ASWP_MULFILE             = SmartWebView.ASWP_MULFILE;
  106.     static boolean ASWP_LOCATION            = SmartWebView.ASWP_LOCATION;
  107.     static boolean ASWP_RATINGS             = SmartWebView.ASWP_RATINGS;
  108.     static boolean ASWP_PULLFRESH           = SmartWebView.ASWP_PULLFRESH;
  109.     static boolean ASWP_PBAR                = SmartWebView.ASWP_PBAR;
  110.     static boolean ASWP_ZOOM                = SmartWebView.ASWP_ZOOM;
  111.     static boolean ASWP_SFORM               = SmartWebView.ASWP_SFORM;
  112.     static boolean ASWP_OFFLINE             = SmartWebView.ASWP_OFFLINE;
  113.     static boolean ASWP_EXTURL              = SmartWebView.ASWP_EXTURL;
  114.     static boolean ASWP_ADMOB               = SmartWebView.ASWP_ADMOB;
  115.     static boolean ASWP_TAB                 = SmartWebView.ASWP_TAB;
  116.     static boolean ASWP_EXITDIAL            = SmartWebView.ASWP_EXITDIAL;
  117.     static boolean ASWP_CP                  = SmartWebView.ASWP_CP;
  118.  
  119.     // security variables
  120.     static boolean ASWP_CERT_VERIFICATION   = SmartWebView.ASWP_CERT_VERI;
  121.  
  122.     // configuration variables
  123.     private static String ASWV_URL          = SmartWebView.ASWV_URL;
  124.     private String CURR_URL                 = ASWV_URL;
  125.     private static String ASWV_SEARCH       = SmartWebView.ASWV_SEARCH;
  126.     private static String ASWV_SHARE_URL    = SmartWebView.ASWV_SHARE_URL;
  127.     private static String ASWV_EXC_LIST     = SmartWebView.ASWV_EXC_LIST;
  128.  
  129.     private static String ASWV_F_TYPE       = SmartWebView.ASWV_F_TYPE;
  130.  
  131.     private static String ASWV_ADMOB        = SmartWebView.ASWV_ADMOB;
  132.  
  133.     public static String ASWV_HOST          = aswm_host(ASWV_URL);
  134.  
  135.     public static int ASWV_FCM_ID           = aswm_fcm_id();
  136.     public static int ASWV_LAYOUT           = SmartWebView.ASWV_LAYOUT;
  137.  
  138.     // user agent variables
  139.     static boolean POSTFIX_USER_AGENT         = SmartWebView.POSTFIX_USER_AGENT;
  140.     static boolean OVERRIDE_USER_AGENT        = SmartWebView.OVERRIDE_USER_AGENT;
  141.     private static String USER_AGENT_POSTFIX  = SmartWebView.USER_AGENT_POSTFIX;
  142.     private static String CUSTOM_USER_AGENT   = SmartWebView.CUSTOM_USER_AGENT;
  143.  
  144.     // careful with these variable names if altering
  145.     WebView asw_view;
  146.     WebView print_view;
  147.     AdView asw_ad_view;
  148.     ProgressBar asw_progress;
  149.     TextView asw_loading_text;
  150.     NotificationManager asw_notification;
  151.     Notification asw_notification_new;
  152.     int asw_error_counter = 0;
  153.  
  154.     Boolean true_online = !ASWP_OFFLINE && !ASWV_URL.startsWith("file:///");
  155.  
  156.     private String asw_pcam_message,asw_vcam_message;
  157.     private ValueCallback<Uri> asw_file_message;
  158.     private ValueCallback<Uri[]> asw_file_path;
  159.     private final static int asw_file_req = 1;
  160.  
  161.     private final static int loc_perm = 1;
  162.     private final static int file_perm = 2;
  163.  
  164.     public static String asw_fcm_channel = "1";
  165.     public String fcm_token;
  166.  
  167.     private SecureRandom random = new SecureRandom();
  168.  
  169.     private static final String TAG = MainActivity.class.getSimpleName();
  170.  
  171.     @Override
  172.     protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  173.         super.onActivityResult(requestCode, resultCode, intent);
  174.  
  175.         if (Build.VERSION.SDK_INT >= 21) {
  176.             getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
  177.             getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
  178.             Uri[] results = null;
  179.             if (resultCode == Activity.RESULT_CANCELED) {
  180.                 if (requestCode == asw_file_req) {
  181.                     // If the file request was cancelled (i.e. user exited camera),
  182.                     // we must still send a null value in order to ensure that future attempts
  183.                     // to pick files will still work.
  184.                     asw_file_path.onReceiveValue(null);
  185.                     return;
  186.                 }
  187.             }
  188.             if (resultCode == Activity.RESULT_OK) {
  189.                 if (requestCode == asw_file_req) {
  190.                     if (null == asw_file_path) {
  191.                         return;
  192.                     }
  193.                     ClipData clipData;
  194.                     String stringData;
  195.                     try {
  196.                         clipData = intent.getClipData();
  197.                         stringData = intent.getDataString();
  198.                     }catch (Exception e){
  199.                         clipData = null;
  200.                         stringData = null;
  201.                     }
  202.  
  203.                     if (clipData == null && stringData == null && (asw_pcam_message != null || asw_vcam_message != null)) {
  204.                         results = new Uri[]{Uri.parse(asw_pcam_message != null ? asw_pcam_message:asw_vcam_message)};
  205.  
  206.                     } else {
  207.                         if (null != clipData) { // checking if multiple files selected or not
  208.                             final int numSelectedFiles = clipData.getItemCount();
  209.                             results = new Uri[numSelectedFiles];
  210.                             for (int i = 0; i < clipData.getItemCount(); i++) {
  211.                                 results[i] = clipData.getItemAt(i).getUri();
  212.                             }
  213.                         } else {
  214.                             try {
  215.                                 Bitmap cam_photo = (Bitmap) intent.getExtras().get("data");
  216.                                 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  217.                                 cam_photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
  218.                                 stringData = MediaStore.Images.Media.insertImage(this.getContentResolver(), cam_photo, null, null);
  219.                             }catch (Exception ignored){}
  220.                             results = new Uri[]{Uri.parse(stringData)};
  221.                         }
  222.                     }
  223.                 }
  224.             }
  225.             asw_file_path.onReceiveValue(results);
  226.             asw_file_path = null;
  227.  
  228.         } else {
  229.             if (requestCode == asw_file_req) {
  230.                 if (null == asw_file_message) return;
  231.                 Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
  232.                 asw_file_message.onReceiveValue(result);
  233.                 asw_file_message = null;
  234.             }
  235.         }
  236.     }
  237.  
  238.     @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast", "JavascriptInterface"})
  239.     @Override
  240.     protected void onCreate(Bundle savedInstanceState) {
  241.         super.onCreate(savedInstanceState);
  242.  
  243.         // ------ PLAY AREA :: for debug purposes only ------ //
  244.  
  245.         // ------- PLAY AREA END ------ //
  246.  
  247.         // use Service Worker
  248.         if (Build.VERSION.SDK_INT >= 24) {
  249.             ServiceWorkerController swController = ServiceWorkerController.getInstance();
  250.             swController.setServiceWorkerClient(new ServiceWorkerClient() {
  251.                 @Override
  252.                 public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) {
  253.                 return null;
  254.                 }
  255.             });
  256.         }
  257.  
  258.         // prevent app from being started again when it is still alive in the background
  259.         if (!isTaskRoot()) {
  260.             finish();
  261.             return;
  262.         }
  263.  
  264.         if(ASWV_LAYOUT==1){
  265.             setContentView(R.layout.drawer_main);
  266.             findViewById(R.id.app_bar).setVisibility(View.VISIBLE);
  267.  
  268.             Toolbar toolbar = findViewById(R.id.toolbar);
  269.             setSupportActionBar(toolbar);
  270.             Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
  271.  
  272.             DrawerLayout drawer = findViewById(R.id.drawer_layout);
  273.             ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(MainActivity.this, drawer, toolbar, R.string.open, R.string.close);
  274.             drawer.addDrawerListener(toggle);
  275.             toggle.syncState();
  276.  
  277.             NavigationView navigationView = findViewById(R.id.nav_view);
  278.             navigationView.setNavigationItemSelectedListener(MainActivity.this);
  279.         }else{
  280.             setContentView(R.layout.activity_main);
  281.         }
  282.  
  283.         asw_view = findViewById(R.id.msw_view);
  284.         print_view = (WebView) findViewById(R.id.print_view); //view on which you want to take a printout
  285.         //asw_view.addJavascriptInterface(new JSInterface(), "JSOUT");
  286.         //asw_view.addJavascriptInterface(new MainActivity.WebViewJavaScriptInterface(this), "androidapp"); //
  287.         // "androidapp is used to call methods exposed from javascript interface, in this example case print
  288.         // method can be called by androidapp.print(String)"
  289.         // load your data from the URL in web view
  290.  
  291.         // requesting new FCM token; updating final cookie variable
  292.         fcm_token();
  293.  
  294.         // notification manager
  295.         NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  296.  
  297.         if(Build.VERSION.SDK_INT >= 26) {
  298.             NotificationChannel notificationChannel = new NotificationChannel(asw_fcm_channel,String.valueOf(R.string.notification_channel_name),NotificationManager.IMPORTANCE_HIGH);
  299.             notificationChannel.setDescription(String.valueOf(R.string.notification_channel_desc));
  300.             notificationChannel.setLightColor(Color.RED);
  301.             notificationChannel.enableVibration(true);
  302.             notificationChannel.setShowBadge(true);
  303.             assert notificationManager != null;
  304.             notificationManager.createNotificationChannel(notificationChannel);
  305.             notificationManager.createNotificationChannel(notificationChannel);
  306.         }
  307.  
  308.         // swipe refresh
  309.         final SwipeRefreshLayout pullfresh = findViewById(R.id.pullfresh);
  310.         if (ASWP_PULLFRESH) {
  311.             pullfresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
  312.                 @Override
  313.                 public void onRefresh() {
  314.                     pull_fresh();
  315.                     pullfresh.setRefreshing(false);
  316.                 }
  317.             });
  318.             asw_view.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
  319.                 @Override
  320.                 public void onScrollChanged() {
  321.                     if (asw_view.getScrollY() == 0) {
  322.                         pullfresh.setEnabled(true);
  323.                     } else {
  324.                         pullfresh.setEnabled(false);
  325.                     }
  326.                 }
  327.             });
  328.         }else{
  329.             pullfresh.setRefreshing(false);
  330.             pullfresh.setEnabled(false);
  331.         }
  332.  
  333.         if (ASWP_PBAR) {
  334.             asw_progress = findViewById(R.id.msw_progress);
  335.         } else {
  336.             findViewById(R.id.msw_progress).setVisibility(View.GONE);
  337.         }
  338.         asw_loading_text = findViewById(R.id.msw_loading_text);
  339.         Handler handler = new Handler();
  340.  
  341.         //Launching app rating request
  342.         if (ASWP_RATINGS) {
  343.             handler.postDelayed(new Runnable() { public void run() { get_rating(); }}, 1000 * 60); //running request after few moments
  344.         }
  345.  
  346.         //Getting basic device information
  347.         get_info();
  348.  
  349.         //Getting GPS location of device if given permission
  350.         if(ASWP_LOCATION && !check_permission(1)){
  351.             ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, loc_perm);
  352.         }
  353.         get_location();
  354.  
  355.         //Webview settings; defaults are customized for best performance
  356.         WebSettings webSettings = asw_view.getSettings();
  357.  
  358.         // setting custom user agent
  359.         if (OVERRIDE_USER_AGENT || POSTFIX_USER_AGENT) {
  360.             String userAgent = webSettings.getUserAgentString();
  361.             if (OVERRIDE_USER_AGENT) {
  362.                 userAgent = CUSTOM_USER_AGENT;
  363.             }
  364.             if (POSTFIX_USER_AGENT) {
  365.                 userAgent = userAgent + " " + USER_AGENT_POSTFIX;
  366.             }
  367.             webSettings.setUserAgentString(userAgent);
  368.         }
  369.  
  370.         if(!ASWP_OFFLINE){
  371.             webSettings.setJavaScriptEnabled(ASWP_JSCRIPT);
  372.         }
  373.         webSettings.setSaveFormData(ASWP_SFORM);
  374.         webSettings.setSupportZoom(ASWP_ZOOM);
  375.         webSettings.setGeolocationEnabled(ASWP_LOCATION);
  376.         webSettings.setAllowFileAccess(true);
  377.         webSettings.setAllowFileAccessFromFileURLs(true);
  378.         webSettings.setAllowUniversalAccessFromFileURLs(true);
  379.         webSettings.setUseWideViewPort(true);
  380.         webSettings.setDomStorageEnabled(true);
  381.  
  382.         if(!ASWP_CP) {
  383.             asw_view.setOnLongClickListener(new View.OnLongClickListener() {
  384.                 @Override
  385.                 public boolean onLongClick(View v) {
  386.                     return true;
  387.                 }
  388.             });
  389.         }
  390.         asw_view.setHapticFeedbackEnabled(false);
  391.  
  392.         // download listener
  393.         asw_view.setDownloadListener(new DownloadListener() {
  394.             @Override
  395.             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
  396.  
  397.                 if(!check_permission(2)){
  398.                     ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, file_perm);
  399.                 }else {
  400.                     DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
  401.  
  402.                     request.setMimeType(mimeType);
  403.                     String cookies = CookieManager.getInstance().getCookie(url);
  404.                     request.addRequestHeader("cookie", cookies);
  405.                     request.addRequestHeader("User-Agent", userAgent);
  406.                     request.setDescription(getString(R.string.dl_downloading));
  407.                     request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
  408.                     request.allowScanningByMediaScanner();
  409.                     request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
  410.                     request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
  411.                     DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
  412.                     assert dm != null;
  413.                     dm.enqueue(request);
  414.                     Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2), Toast.LENGTH_LONG).show();
  415.                 }
  416.             }
  417.         });
  418.  
  419.         getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
  420.         getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
  421.         webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
  422.         asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
  423.         asw_view.setVerticalScrollBarEnabled(false);
  424.         asw_view.setWebViewClient(new Callback());
  425.  
  426.         //Reading incoming intents
  427.         Intent read_int = getIntent();
  428.         Log.d("INTENT", read_int.toUri(0));
  429.         String uri = read_int.getStringExtra("uri");
  430.         String share = read_int.getStringExtra("s_uri");
  431.         String share_img = read_int.getStringExtra("s_img");
  432.  
  433.         if(share != null) {
  434.             //Processing shared content
  435.             Log.d("SHARE INTENT",share);
  436.             Matcher matcher = urlPattern.matcher(share);
  437.             String urlStr = "";
  438.             if(matcher.find()){
  439.                 urlStr = matcher.group();
  440.                 if(urlStr.startsWith("(") && urlStr.endsWith(")")) {
  441.                     urlStr = urlStr.substring(1, urlStr.length() - 1);
  442.                 }
  443.             }
  444.             String red_url = ASWV_SHARE_URL+"?text="+share+"&link="+urlStr+"&image_url=";
  445.             //Toast.makeText(MainActivity.this, "SHARE: "+red_url+"\nLINK: "+urlStr, Toast.LENGTH_LONG).show();
  446.             aswm_view(red_url, false, asw_error_counter);
  447.  
  448.         }else if(share_img != null) {
  449.             //Processing shared content
  450.             Log.d("SHARE INTENT",share_img);
  451.             Toast.makeText(MainActivity.this, share_img, Toast.LENGTH_LONG).show();
  452.             aswm_view(ASWV_URL, false, asw_error_counter);
  453.  
  454.         }else if(uri != null) {
  455.             //Opening notification
  456.             Log.d("NOTIFICATION INTENT",uri);
  457.             aswm_view(uri, false, asw_error_counter);
  458.  
  459.         }else{
  460.             //Rendering the default URL
  461.             Log.d("MAIN INTENT",ASWV_URL);
  462.             aswm_view(ASWV_URL, false, asw_error_counter);
  463.         }
  464.  
  465.         if(ASWP_ADMOB) {
  466.             MobileAds.initialize(this, new OnInitializationCompleteListener() {
  467.                 @Override
  468.                 public void onInitializationComplete(InitializationStatus initializationStatus){}
  469.             });
  470.             //List<String> testDeviceIds = Arrays.asList("4C304B10577C757E3A3C3B667FF84F8C");
  471.             //RequestConfiguration configuration = new RequestConfiguration.Builder().setTestDeviceIds(testDeviceIds).build();
  472.             //MobileAds.setRequestConfiguration(configuration);
  473.             //MobileAds.setRequestConfiguration(new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("4C304B10577C757E3A3C3B667FF84F8C")).build());
  474.             asw_ad_view = findViewById(R.id.msw_ad_view);
  475.             AdRequest adRequest = new AdRequest.Builder().build();
  476.             asw_ad_view.loadAd(adRequest);
  477.         }
  478.  
  479.         asw_view.setWebChromeClient(new WebChromeClient() {
  480.             // handling input[type="file"]
  481.             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams){
  482.                 if(check_permission(2) && check_permission(3)) {
  483.                     if (ASWP_FUPLOAD) {
  484.                         asw_file_path = filePathCallback;
  485.                         Intent takePictureIntent = null;
  486.                         Intent takeVideoIntent = null;
  487.                         if (ASWP_CAMUPLOAD) {
  488.                             boolean includeVideo = false;
  489.                             boolean includePhoto = false;
  490.  
  491.                             // Check the accept parameter to determine which intent(s) to include.
  492.                             paramCheck:
  493.                             for (String acceptTypes : fileChooserParams.getAcceptTypes()) {
  494.                                 // Although it's an array, it still seems to be the whole value.
  495.                                 // Split it out into chunks so that we can detect multiple values.
  496.                                 String[] splitTypes = acceptTypes.split(", ?+");
  497.                                 for (String acceptType : splitTypes) {
  498.                                     switch (acceptType) {
  499.                                         case "*/*":
  500.                                             includePhoto = true;
  501.                                             includeVideo = true;
  502.                                             break paramCheck;
  503.                                         case "image/*":
  504.                                             includePhoto = true;
  505.                                             break;
  506.                                         case "video/*":
  507.                                             includeVideo = true;
  508.                                             break;
  509.                                     }
  510.                                 }
  511.                             }
  512.  
  513.                             // If no `accept` parameter was specified, allow both photo and video.
  514.                             if (fileChooserParams.getAcceptTypes().length == 0) {
  515.                                 includePhoto = true;
  516.                                 includeVideo = true;
  517.                             }
  518.  
  519.                             if (includePhoto) {
  520.                                 takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  521.                                 if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
  522.                                     File photoFile = null;
  523.                                     try {
  524.                                         photoFile = create_image();
  525.                                         takePictureIntent.putExtra("PhotoPath", asw_pcam_message);
  526.                                     } catch (IOException ex) {
  527.                                         Log.e(TAG, "Image file creation failed", ex);
  528.                                     }
  529.                                     if (photoFile != null) {
  530.                                         asw_pcam_message = "file:" + photoFile.getAbsolutePath();
  531.                                         takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
  532.                                     } else {
  533.                                         takePictureIntent = null;
  534.                                     }
  535.                                 }
  536.                             }
  537.  
  538.                             if (includeVideo) {
  539.                                 takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
  540.                                 if (takeVideoIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
  541.                                     File videoFile = null;
  542.                                     try {
  543.                                         videoFile = create_video();
  544.                                     } catch (IOException ex) {
  545.                                         Log.e(TAG, "Video file creation failed", ex);
  546.                                     }
  547.                                     if (videoFile != null) {
  548.                                         asw_vcam_message = "file:" + videoFile.getAbsolutePath();
  549.                                         takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));
  550.                                     } else {
  551.                                         takeVideoIntent = null;
  552.                                     }
  553.                                 }
  554.                             }
  555.                         }
  556.  
  557.                         Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
  558.                         if (!ASWP_ONLYCAM) {
  559.                             contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
  560.                             contentSelectionIntent.setType(ASWV_F_TYPE);
  561.                             if (ASWP_MULFILE) {
  562.                                 contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
  563.                             }
  564.                         }
  565.                         Intent[] intentArray;
  566.                         if (takePictureIntent != null && takeVideoIntent != null) {
  567.                             intentArray = new Intent[]{takePictureIntent, takeVideoIntent};
  568.                         } else if (takePictureIntent != null) {
  569.                             intentArray = new Intent[]{takePictureIntent};
  570.                         } else if (takeVideoIntent != null) {
  571.                             intentArray = new Intent[]{takeVideoIntent};
  572.                         } else {
  573.                             intentArray = new Intent[0];
  574.                         }
  575.  
  576.                         Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
  577.                         chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
  578.                         chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.fl_chooser));
  579.                         chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
  580.                         startActivityForResult(chooserIntent, asw_file_req);
  581.                     }
  582.                     return true;
  583.                 }else{
  584.                     get_file();
  585.                     return false;
  586.                 }
  587.             }
  588.  
  589.             //Getting webview rendering progress
  590.             @Override
  591.             public void onProgressChanged(WebView view, int p) {
  592.                 if (ASWP_PBAR) {
  593.                     asw_progress.setProgress(p);
  594.                     if (p == 100) {
  595.                         asw_progress.setProgress(0);
  596.                     }
  597.                 }
  598.             }
  599.  
  600.             // overload the geoLocations permissions prompt to always allow instantly as app permission was granted previously
  601.             public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
  602.                 if(Build.VERSION.SDK_INT < 23 || check_permission(1)){
  603.                     // location permissions were granted previously so auto-approve
  604.                     callback.invoke(origin, true, false);
  605.                 } else {
  606.                     // location permissions not granted so request them
  607.                     ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, loc_perm);
  608.                 }
  609.             }
  610.         });
  611.         if (getIntent().getData() != null) {
  612.             String path     = getIntent().getDataString();
  613.             /*
  614.             If you want to check or use specific directories or schemes or hosts
  615.             Uri data        = getIntent().getData();
  616.             String scheme   = data.getScheme();
  617.             String host     = data.getHost();
  618.             List<String> pr = data.getPathSegments();
  619.             String param1   = pr.get(0);
  620.             */
  621.             aswm_view(path, false, asw_error_counter);
  622.         }
  623.     }
  624.  
  625.     public class WebViewJavaScriptInterface {
  626.         WebViewJavaScriptInterface(Context context) {
  627.             /*public void print(final String data){
  628.                 runOnUiThread(() -> doWebViewPrint(data));
  629.             }*/
  630.         }
  631.     }
  632.  
  633.     private void doWebViewPrint(String ss) {
  634.         print_view.setWebViewClient(new WebViewClient() {
  635.  
  636.             public boolean shouldOverrideUrlLoading(WebView view, String url) {
  637.                 return false;
  638.             }
  639.  
  640.             //use Service Worker
  641.             @Nullable
  642.             @Override
  643.             public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
  644.                 return super.shouldInterceptRequest(view, request);
  645.             }
  646.  
  647.             @Override
  648.             public void onPageFinished(WebView view, String url) {
  649.                 print_page(view,view.getTitle(),false);
  650.                 super.onPageFinished(view, url);
  651.             }
  652.         });
  653.         // Generate an HTML document on the fly:
  654.         print_view.loadDataWithBaseURL(null, ss, "text/html", "UTF-8", null);
  655.     }
  656.  
  657.     @Override
  658.     public void onPause() {
  659.         super.onPause();
  660.         asw_view.onPause();
  661.     }
  662.  
  663.     @Override
  664.     public void onResume() {
  665.         super.onResume();
  666.         asw_view.onResume();
  667.         //Coloring the "recent apps" tab header; doing it onResume, as an insurance
  668.         if (Build.VERSION.SDK_INT >= 23) {
  669.             Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
  670.             ActivityManager.TaskDescription taskDesc;
  671.             taskDesc = new ActivityManager.TaskDescription(getString(R.string.app_name), bm, getColor(R.color.colorPrimary));
  672.             MainActivity.this.setTaskDescription(taskDesc);
  673.         }
  674.         get_location();
  675.     }
  676.  
  677.     //Setting activity layout visibility
  678.     private class Callback extends WebViewClient {
  679.         public void onPageStarted(WebView view, String url, Bitmap favicon) {
  680.             get_location();
  681.         }
  682.  
  683.         public void onPageFinished(WebView view, String url) {
  684.             findViewById(R.id.msw_welcome).setVisibility(View.GONE);
  685.             findViewById(R.id.msw_view).setVisibility(View.VISIBLE);
  686.         }
  687.         //For android below API 23
  688.         @Override
  689.         public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
  690.             Toast.makeText(getApplicationContext(), getString(R.string.went_wrong), Toast.LENGTH_SHORT).show();
  691.             aswm_view("file:///android_asset/error.html", false, asw_error_counter);
  692.         }
  693.  
  694.         //Overriding webview URLs
  695.         @Override
  696.         public boolean shouldOverrideUrlLoading(WebView view, String url) {
  697.             CURR_URL = url;
  698.             return url_actions(view, url);
  699.         }
  700.  
  701.         //Overriding webview URLs for API 23+ [suggested by github.com/JakePou]
  702.         @TargetApi(Build.VERSION_CODES.N)
  703.         @Override
  704.         public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
  705.             CURR_URL = request.getUrl().toString();
  706.             return url_actions(view, request.getUrl().toString());
  707.         }
  708.  
  709.         @Override
  710.         public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
  711.             if(ASWP_CERT_VERIFICATION) {
  712.                 super.onReceivedSslError(view, handler, error);
  713.             } else {
  714.                 handler.proceed(); // Ignore SSL certificate errors
  715.             }
  716.         }
  717.     }
  718.  
  719.     //Random ID creation function to help get fresh cache every-time webview reloaded
  720.     public String random_id() {
  721.         return new BigInteger(130, random).toString(32);
  722.     }
  723.  
  724.     //Opening URLs inside webview with request
  725.     void aswm_view(String url, Boolean tab, int error_counter) {
  726.         if(error_counter > 2){
  727.             asw_error_counter = 0;
  728.             aswm_exit();
  729.         }else {
  730.             if(tab){
  731.                 if(ASWP_TAB) {
  732.                     CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder();
  733.                     intentBuilder.setToolbarColor(ContextCompat.getColor(this, R.color.colorPrimary));
  734.                     intentBuilder.setSecondaryToolbarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
  735.                     intentBuilder.setStartAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right);
  736.                     intentBuilder.setExitAnimations(this, android.R.anim.slide_in_left, android.R.anim.slide_out_right);
  737.                     CustomTabsIntent customTabsIntent = intentBuilder.build();
  738.                     try {
  739.                         customTabsIntent.launchUrl(MainActivity.this, Uri.parse(url));
  740.                     } catch (ActivityNotFoundException e) {
  741.                         Intent intent = new Intent(Intent.ACTION_VIEW);
  742.                         intent.setData(Uri.parse(url));
  743.                         startActivity(intent);
  744.                     }
  745.                 }else{
  746.                     Intent intent = new Intent(Intent.ACTION_VIEW);
  747.                     intent.setData(Uri.parse(url));
  748.                     startActivity(intent);
  749.                 }
  750.             } else {
  751.                 if (url.contains("?")) { // check to see whether the url already has query parameters and handle appropriately.
  752.                     url += "&";
  753.                 } else {
  754.                     url += "?";
  755.                 }
  756.                 url += "rid=" + random_id();
  757.                 asw_view.loadUrl(url);
  758.             }
  759.         }
  760.     }
  761.  
  762.     /*--- actions based on URL structure ---*/
  763.  
  764.     public boolean url_actions(WebView view, String url){
  765.         boolean a = true;
  766.         // show toast error if not connected to the network
  767.         if (!ASWP_OFFLINE && !DetectConnection.isInternetAvailable(MainActivity.this)) {
  768.             Toast.makeText(getApplicationContext(), getString(R.string.check_connection), Toast.LENGTH_SHORT).show();
  769.  
  770.         // use this in a hyperlink to redirect back to default URL :: href="refresh:android"
  771.         } else if (url.startsWith("refresh:")) {
  772.             String ref_sch = (Uri.parse(url).toString()).replace("refresh:","");
  773.             if(ref_sch.matches("URL")){
  774.                 CURR_URL = ASWV_URL;
  775.             }
  776.             pull_fresh();
  777.  
  778.         // use this in a hyperlink to launch default phone dialer for specific number :: href="tel:+919876543210"
  779.         } else if (url.startsWith("tel:")) {
  780.             Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
  781.             startActivity(intent);
  782.  
  783.         } else if(url.startsWith("print:")) {
  784.             print_page(view,view.getTitle(),true);
  785.  
  786.         // use this to open your apps page on google play store app :: href="rate:android"
  787.         } else if (url.startsWith("rate:")) {
  788.             final String app_package = getPackageName(); //requesting app package name from Context or Activity object
  789.             try {
  790.                 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + app_package)));
  791.             } catch (ActivityNotFoundException anfe) {
  792.                 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + app_package)));
  793.             }
  794.  
  795.         // sharing content from your webview to external apps :: href="share:URL" and remember to place the URL you want to share after share:___
  796.         } else if (url.startsWith("share:")) {
  797.             Intent intent = new Intent(Intent.ACTION_SEND);
  798.             intent.setType("text/plain");
  799.             intent.putExtra(Intent.EXTRA_SUBJECT, view.getTitle());
  800.             intent.putExtra(Intent.EXTRA_TEXT, view.getTitle()+"\nVisit: "+(Uri.parse(url).toString()).replace("share:",""));
  801.             startActivity(Intent.createChooser(intent, getString(R.string.share_w_friends)));
  802.  
  803.         // use this in a hyperlink to exit your app :: href="exit:android"
  804.         } else if (url.startsWith("exit:")) {
  805.             aswm_exit();
  806.  
  807.         // getting location for offline files
  808.         } else if (url.startsWith("offloc:")) {
  809.             String offloc = ASWV_URL+"?loc="+get_location();
  810.             aswm_view(offloc,false, asw_error_counter);
  811.             Log.d("OFFLINE LOC REQ",offloc);
  812.  
  813.         // creating firebase notification for offline files
  814.         } else if (url.startsWith("fcm:")) {
  815.             String fcm = ASWV_URL + "?fcm=" + fcm_token();
  816.             aswm_view(fcm, false, asw_error_counter);
  817.             Log.d("OFFLINE_FCM_TOKEN", fcm);
  818.  
  819.  
  820.         // opening external URLs in android default web browser
  821.         } else if (ASWP_EXTURL && !aswm_host(url).equals(ASWV_HOST) && !ASWV_EXC_LIST.contains(aswm_host(url))) {
  822.             aswm_view(url,true, asw_error_counter);
  823.  
  824.         // else return false for no special action
  825.         } else {
  826.             a = false;
  827.         }
  828.         return a;
  829.     }
  830.  
  831.     //Getting host name
  832.     public static String aswm_host(String url){
  833.         if (url == null || url.length() == 0) {
  834.             return "";
  835.         }
  836.         int dslash = url.indexOf("//");
  837.         if (dslash == -1) {
  838.             dslash = 0;
  839.         } else {
  840.             dslash += 2;
  841.         }
  842.         int end = url.indexOf('/', dslash);
  843.         end = end >= 0 ? end : url.length();
  844.         int port = url.indexOf(':', dslash);
  845.         end = (port > 0 && port < end) ? port : end;
  846.         Log.w("URL Host: ",url.substring(dslash, end));
  847.         return url.substring(dslash, end);
  848.     }
  849.  
  850.     //Reloading current page
  851.     public void pull_fresh(){
  852.         aswm_view((!CURR_URL.equals("")?CURR_URL:ASWV_URL),false, asw_error_counter);
  853.     }
  854.  
  855.     //Getting device basic information
  856.     public void get_info(){
  857.         if(true_online) {
  858.             fcm_token();
  859.             CookieManager cookieManager = CookieManager.getInstance();
  860.             cookieManager.setAcceptCookie(true);
  861.             cookieManager.setCookie(ASWV_URL, "DEVICE=android");
  862.             DeviceDetails dv = new DeviceDetails();
  863.             cookieManager.setCookie(ASWV_URL, "DEVICE_INFO=" + dv.pull());
  864.  
  865.             cookieManager.setCookie(ASWV_URL, "DEV_API=" + Build.VERSION.SDK_INT);
  866.  
  867.             cookieManager.setCookie(ASWV_URL, "APP_ID=" + BuildConfig.APPLICATION_ID);
  868.             cookieManager.setCookie(ASWV_URL, "APP_VER=" + BuildConfig.VERSION_CODE + "/" + BuildConfig.VERSION_NAME);
  869.             Log.d("COOKIES: ", cookieManager.getCookie(ASWV_URL));
  870.         }
  871.     }
  872.  
  873.     //Checking permission for storage and camera for writing and uploading images
  874.     public void get_file(){
  875.         String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
  876.  
  877.         //Checking for storage permission to write images for upload
  878.         if (ASWP_FUPLOAD && ASWP_CAMUPLOAD && !check_permission(2) && !check_permission(3)) {
  879.             ActivityCompat.requestPermissions(MainActivity.this, perms, file_perm);
  880.  
  881.         //Checking for WRITE_EXTERNAL_STORAGE permission
  882.         } else if (ASWP_FUPLOAD && !check_permission(2)) {
  883.             ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, file_perm);
  884.  
  885.         //Checking for CAMERA permissions
  886.         } else if (ASWP_CAMUPLOAD && !check_permission(3)) {
  887.             ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, file_perm);
  888.         }
  889.     }
  890.  
  891.     //Using cookies to update user locations
  892.     public String get_location(){
  893.         String newloc = "0,0";
  894.         //Checking for location permissions
  895.         if (ASWP_LOCATION && (Build.VERSION.SDK_INT < 23 || check_permission(1))) {
  896.             GPSTrack gps;
  897.             gps = new GPSTrack(MainActivity.this);
  898.             double latitude = gps.getLatitude();
  899.             double longitude = gps.getLongitude();
  900.             if (gps.canGetLocation()) {
  901.                 if (latitude != 0 || longitude != 0) {
  902.                     if(true_online) {
  903.                         CookieManager cookieManager = CookieManager.getInstance();
  904.                         cookieManager.setAcceptCookie(true);
  905.                         cookieManager.setCookie(ASWV_URL, "lat=" + latitude);
  906.                         cookieManager.setCookie(ASWV_URL, "long=" + longitude);
  907.                         cookieManager.setCookie(ASWV_URL, "LATLANG=" + latitude + "x" + longitude);
  908.                     }
  909.                     //Log.w("New Updated Location:", latitude + "," + longitude);  //enable to test dummy latitude and longitude
  910.                     newloc = latitude+","+longitude;
  911.                 } else {
  912.                     Log.w("New Updated Location:", "NULL");
  913.                 }
  914.             } else {
  915.                 show_notification(1, 1);
  916.                 Log.w("New Updated Location:", "FAIL");
  917.             }
  918.         }
  919.         return newloc;
  920.     }
  921.  
  922.     // get cookie value
  923.     public String get_cookies(String cookie){
  924.         String value = "";
  925.         CookieManager cookieManager = CookieManager.getInstance();
  926.         String cookies = cookieManager.getCookie(ASWV_URL);
  927.         String[] temp=cookies.split(";");
  928.         for (String ar1 : temp ){
  929.             if(ar1.contains(cookie)){
  930.                 String[] temp1=ar1.split("=");
  931.                 value = temp1[1];
  932.                 break;
  933.             }
  934.         }
  935.         return value;
  936.     }
  937.  
  938.     private static final Pattern urlPattern = Pattern.compile(
  939.             "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"+"(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"+"[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  940.  
  941.     @SuppressLint("ResourceAsColor")
  942.     @Override
  943.     public boolean onCreateOptionsMenu(Menu menu) {
  944.         // Inflate the menu; this adds items to the action bar if it is present.
  945.         getMenuInflater().inflate(R.menu.main, menu);
  946.         SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
  947.         final SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
  948.         searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
  949.         searchView.setQueryHint(getString(R.string.search_hint));
  950.         searchView.setIconified(true);
  951.         searchView.setIconifiedByDefault(true);
  952.         searchView.clearFocus();
  953.  
  954.         searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
  955.             @Override
  956.             public boolean onQueryTextSubmit(String query) {
  957.                 searchView.clearFocus();
  958.                 aswm_view(ASWV_SEARCH+query,false,asw_error_counter);
  959.                 searchView.setQuery(query,false);
  960.                 return false;
  961.             }
  962.             @Override
  963.             public boolean onQueryTextChange(String query) {
  964.                 return false;
  965.             }
  966.         });
  967.         //searchView.setQuery(asw_view.getUrl(),false);
  968.         return true;
  969.     }
  970.  
  971.     @Override
  972.     public boolean onOptionsItemSelected(MenuItem item) {
  973.         int id = item.getItemId();
  974.         if (id == R.id.action_exit) {
  975.             aswm_exit();
  976.             return true;
  977.         }
  978.         return super.onOptionsItemSelected(item);
  979.     }
  980.  
  981.     public boolean onNavigationItemSelected(MenuItem item) {
  982.         int id = item.getItemId();
  983.         if (id == R.id.nav_home) {
  984.             aswm_view("https://github.com",false,asw_error_counter);
  985.         } else if (id == R.id.nav_doc) {
  986.             aswm_view("https://github.com",false,asw_error_counter);
  987.         } else if (id == R.id.nav_fcm) {
  988.             aswm_view("https://github.com",false,asw_error_counter);
  989.         } else if (id == R.id.nav_admob) {
  990.             aswm_view("https://github.com",false,asw_error_counter);
  991.         } else if (id == R.id.nav_gps) {
  992.             aswm_view("https://github.com",false,asw_error_counter);
  993.         } else if (id == R.id.nav_share) {
  994.             aswm_view("https://github.com",false,asw_error_counter);
  995.         } else if (id == R.id.nav_lay) {
  996.             aswm_view("https://github.com",false,asw_error_counter);
  997.         } else if (id == R.id.nav_support) {
  998.             Intent intent = new Intent(Intent.ACTION_SENDTO);
  999.             intent.setData(Uri.parse("https://github.com"));
  1000.             intent.putExtra(Intent.EXTRA_SUBJECT, "SWV Help");
  1001.             startActivity(Intent.createChooser(intent, "Send Email"));
  1002.         }
  1003.  
  1004.         DrawerLayout drawer = findViewById(R.id.drawer_layout);
  1005.         drawer.closeDrawer(GravityCompat.START);
  1006.         return true;
  1007.     }
  1008.  
  1009.     public static int aswm_fcm_id(){
  1010.         //Date now = new Date();
  1011.         //Integer.parseInt(new SimpleDateFormat("ddHHmmss",  Locale.US).format(now));
  1012.         return 1;
  1013.     }
  1014.  
  1015.     public String fcm_token(){
  1016.         FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MainActivity.this, instanceIdResult -> {
  1017.             fcm_token = instanceIdResult.getToken();
  1018.                 if(true_online) {
  1019.                     CookieManager cookieManager = CookieManager.getInstance();
  1020.                     cookieManager.setAcceptCookie(true);
  1021.                     cookieManager.setCookie(ASWV_URL, "FCM_TOKEN="+fcm_token);
  1022.                     Log.d("FCM_BAKED","YES");
  1023.                     //Log.d("COOKIES: ", cookieManager.getCookie(ASWV_URL));
  1024.                 }
  1025.             Log.d("REQ_FCM_TOKEN", fcm_token);
  1026.         }).addOnFailureListener(e -> Log.d("REQ_FCM_TOKEN", "FAILED"));
  1027.         return fcm_token;
  1028.     }
  1029.  
  1030.     //Checking if particular permission is given or not
  1031.     public boolean check_permission(int permission){
  1032.         switch(permission){
  1033.             case 1:
  1034.                 return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
  1035.  
  1036.             case 2:
  1037.                 return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
  1038.  
  1039.             case 3:
  1040.                 return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
  1041.  
  1042.         }
  1043.         return false;
  1044.     }
  1045.  
  1046.     //Creating image file for upload
  1047.     private File create_image() throws IOException {
  1048.         @SuppressLint("SimpleDateFormat")
  1049.         String file_name    = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
  1050.         String new_name     = "file_"+file_name+"_";
  1051.         File sd_directory   = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
  1052.         return File.createTempFile(new_name, ".jpg", sd_directory);
  1053.     }
  1054.  
  1055.     //Creating video file for upload
  1056.     private File create_video() throws IOException {
  1057.         @SuppressLint("SimpleDateFormat")
  1058.         String file_name    = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
  1059.         String new_name     = "file_"+file_name+"_";
  1060.         File sd_directory   = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
  1061.         return File.createTempFile(new_name, ".3gp", sd_directory);
  1062.     }
  1063.  
  1064.     //Launching app rating dialoge [developed by github.com/hotchemi]
  1065.     public void get_rating() {
  1066.         if (DetectConnection.isInternetAvailable(MainActivity.this)) {
  1067.             AppRate.with(this)
  1068.                 .setStoreType(StoreType.GOOGLEPLAY)     //default is Google Play, other option is Amazon App Store
  1069.                 .setInstallDays(SmartWebView.ASWR_DAYS)
  1070.                 .setLaunchTimes(SmartWebView.ASWR_TIMES)
  1071.                 .setRemindInterval(SmartWebView.ASWR_INTERVAL)
  1072.                 .setTitle(R.string.rate_dialog_title)
  1073.                 .setMessage(R.string.rate_dialog_message)
  1074.                 .setTextLater(R.string.rate_dialog_cancel)
  1075.                 .setTextNever(R.string.rate_dialog_no)
  1076.                 .setTextRateNow(R.string.rate_dialog_ok)
  1077.                 .monitor();
  1078.             AppRate.showRateDialogIfMeetsConditions(this);
  1079.         }
  1080.         //for more customizations, look for AppRate and DialogManager
  1081.     }
  1082.  
  1083.     //Creating custom notifications with IDs
  1084.     public void show_notification(int type, int id) {
  1085.         long when = System.currentTimeMillis();
  1086.         asw_notification = (NotificationManager) MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
  1087.         Intent i = new Intent();
  1088.         if (type == 1) {
  1089.             i.setClass(MainActivity.this, MainActivity.class);
  1090.         } else if (type == 2) {
  1091.             i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  1092.         } else {
  1093.             i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  1094.             i.addCategory(Intent.CATEGORY_DEFAULT);
  1095.             i.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
  1096.             i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1097.             i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
  1098.             i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  1099.         }
  1100.         i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  1101.  
  1102.         PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
  1103.  
  1104.         Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
  1105.  
  1106.         NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this, "");
  1107.         switch(type){
  1108.             case 1:
  1109.                 builder.setTicker(getString(R.string.app_name));
  1110.                 builder.setContentTitle(getString(R.string.loc_fail));
  1111.                 builder.setContentText(getString(R.string.loc_fail_text));
  1112.                 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_fail_more)));
  1113.                 builder.setVibrate(new long[]{350,350,350,350,350});
  1114.                 builder.setSmallIcon(R.mipmap.ic_launcher);
  1115.             break;
  1116.  
  1117.             case 2:
  1118.                 builder.setTicker(getString(R.string.app_name));
  1119.                 builder.setContentTitle(getString(R.string.loc_perm));
  1120.                 builder.setContentText(getString(R.string.loc_perm_text));
  1121.                 builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_perm_more)));
  1122.                 builder.setVibrate(new long[]{350, 700, 350, 700, 350});
  1123.                 builder.setSound(alarmSound);
  1124.                 builder.setSmallIcon(R.mipmap.ic_launcher);
  1125.             break;
  1126.         }
  1127.         builder.setOngoing(false);
  1128.         builder.setAutoCancel(true);
  1129.         builder.setContentIntent(pendingIntent);
  1130.         builder.setWhen(when);
  1131.         builder.setContentIntent(pendingIntent);
  1132.         asw_notification_new = builder.build();
  1133.         asw_notification.notify(id, asw_notification_new);
  1134.     }
  1135.  
  1136.     //Printing pages
  1137.     private void print_page(WebView view, String print_name, boolean manual) {
  1138.         PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
  1139.         PrintDocumentAdapter printAdapter = view.createPrintDocumentAdapter(print_name);
  1140.         PrintAttributes.Builder builder = new PrintAttributes.Builder();
  1141.         builder.setMediaSize(PrintAttributes.MediaSize.ISO_A5);
  1142.         PrintJob printJob = printManager.print(print_name, printAdapter, builder.build());
  1143.  
  1144.         if(printJob.isCompleted()){
  1145.             Toast.makeText(getApplicationContext(), R.string.print_complete, Toast.LENGTH_LONG).show();
  1146.         }
  1147.         else if(printJob.isFailed()){
  1148.             Toast.makeText(getApplicationContext(), R.string.print_failed, Toast.LENGTH_LONG).show();
  1149.         }
  1150.     }
  1151.  
  1152.     //Checking if users allowed the requested permissions or not
  1153.     @SuppressLint("MissingSuperCall")
  1154.     @Override
  1155.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
  1156.         if (requestCode == 1) {
  1157.             if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  1158.                 get_location();
  1159.             }
  1160.         }
  1161.     }
  1162.  
  1163.     //Action on back key tap/click
  1164.     @Override
  1165.     public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
  1166.         if (event.getAction() == KeyEvent.ACTION_DOWN) {
  1167.             if (keyCode == KeyEvent.KEYCODE_BACK) {
  1168.                 if (asw_view.canGoBack()) {
  1169.                     asw_view.goBack();
  1170.                 } else {
  1171.                     if(ASWP_EXITDIAL) {
  1172.                         ask_exit();
  1173.                     }else{
  1174.                         finish();
  1175.                     }
  1176.                 }
  1177.                 return true;
  1178.             }
  1179.         }
  1180.         return super.onKeyDown(keyCode, event);
  1181.     }
  1182.  
  1183.     public void aswm_exit(){
  1184.         Intent intent = new Intent(Intent.ACTION_MAIN);
  1185.         intent.addCategory(Intent.CATEGORY_HOME);
  1186.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1187.         startActivity(intent);
  1188.     }
  1189.  
  1190.     // Creating exit dialogue
  1191.     public void ask_exit(){
  1192.         AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
  1193.  
  1194.         builder.setTitle(getString(R.string.exit_title));
  1195.         builder.setMessage(getString(R.string.exit_subtitle));
  1196.         builder.setCancelable(true);
  1197.  
  1198.         // Action if user selects 'yes'
  1199.         builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
  1200.             @Override
  1201.             public void onClick(DialogInterface dialogInterface, int i) {
  1202.                 finish();
  1203.             }
  1204.         });
  1205.  
  1206.         // Actions if user selects 'no'
  1207.         builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
  1208.             @Override
  1209.             public void onClick(DialogInterface dialogInterface, int i) {
  1210.             }
  1211.         });
  1212.  
  1213.         // Create the alert dialog using alert dialog builder
  1214.         AlertDialog dialog = builder.create();
  1215.  
  1216.         // Finally, display the dialog when user press back button
  1217.         dialog.show();
  1218.     }
  1219.  
  1220.     @Override
  1221.     protected void onStart() {
  1222.         super.onStart();
  1223.     }
  1224.  
  1225.     @Override
  1226.     protected void onStop() {
  1227.         super.onStop();
  1228.     }
  1229.  
  1230.     @Override
  1231.     public void onConfigurationChanged(Configuration newConfig) {
  1232.         super.onConfigurationChanged(newConfig);
  1233.     }
  1234.  
  1235.     @Override
  1236.     protected void onSaveInstanceState(Bundle outState ){
  1237.         super.onSaveInstanceState(outState);
  1238.         asw_view.saveState(outState);
  1239.     }
  1240.  
  1241.     @Override
  1242.     protected void onRestoreInstanceState(Bundle savedInstanceState){
  1243.         super.onRestoreInstanceState(savedInstanceState);
  1244.         asw_view.restoreState(savedInstanceState);
  1245.     }
  1246. }
Add Comment
Please, Sign In to add comment