AbiMulya

MainWebView.Java

Nov 30th, 2020
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 36.60 KB | None | 0 0
  1. package com.mdd.unikpay.mainmenu;
  2.  
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.app.Activity;
  6. import android.content.ClipData;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.pm.PackageManager;
  10. import android.content.res.Configuration;
  11. import android.graphics.Bitmap;
  12. import android.net.Uri;
  13. import android.nfc.NfcAdapter;
  14. import android.nfc.NfcManager;
  15. import android.nfc.Tag;
  16. import android.os.AsyncTask;
  17. import android.os.Build;
  18. import android.os.Bundle;
  19. import android.os.CountDownTimer;
  20. import android.os.Environment;
  21. import android.os.StrictMode;
  22. import android.provider.MediaStore;
  23. import android.provider.Settings;
  24. import android.util.Base64;
  25. import android.util.Log;
  26. import android.view.KeyEvent;
  27. import android.view.View;
  28. import android.view.WindowManager;
  29. import android.webkit.JavascriptInterface;
  30. import android.webkit.ValueCallback;
  31. import android.webkit.WebChromeClient;
  32. import android.webkit.WebView;
  33. import android.webkit.WebViewClient;
  34. import android.widget.Toast;
  35.  
  36. import androidx.annotation.NonNull;
  37. import androidx.appcompat.app.AppCompatActivity;
  38. import androidx.core.app.ActivityCompat;
  39. import androidx.core.content.ContextCompat;
  40.  
  41. import com.google.gson.Gson;
  42. import com.mdd.aar.deviceid.AarDeviceId;
  43. import com.mdd.aar.deviceid.DeviceEnvironment;
  44. import com.mdd.aar.deviceid.exceptions.DeviceNotRegisteredException;
  45. import com.mdd.topupUnik.ubal.ApiUtils;
  46. import com.mdd.topupUnik.ubal.InitDebugCertificate;
  47. import com.mdd.topupUnik.ubal.InitReader;
  48. import com.mdd.topupUnik.ubal.MainCardProcessor;
  49. import com.mdd.topupUnik.ubal.SuccessUpdateBalance;
  50. import com.mdd.topupUnik.ubal.UpdateBalanceView;
  51. import com.mdd.topupUnik.ubal.lib.CardInfo;
  52. import com.mdd.topupUnik.ubal.lib.CardInfoCommand;
  53. import com.mdd.topupUnik.ubal.lib.CommandResult;
  54. import com.mdd.unikpay.R;
  55. import com.mdd.unikpay.devices.DevicePrinter;
  56. import com.mdd.unikpay.features.debitkredit.app.TradeApplication;
  57. import com.mdd.unikpay.helpers.UpdateBalanceErrorModel;
  58. import com.mdd.unikpay.mobile.InitListener;
  59. import com.mdd.unikpay.pojos.CalbackModel;
  60. import com.mdd.unikpay.receipt.ReceiptFactory;
  61. import com.medicom.dudikov.mybanklibrary.nativeLib;
  62.  
  63. import java.io.File;
  64. import java.io.IOException;
  65. import java.net.InetAddress;
  66. import java.text.SimpleDateFormat;
  67. import java.util.Date;
  68. import java.util.List;
  69. import java.util.Timer;
  70. import java.util.TimerTask;
  71.  
  72. import id.emhusnan.mdd.service.LibraryConfig;
  73. import id.emhusnan.mdd.service.MDDCommand;
  74. import id.emhusnan.mdd.service.MDDUpdateBalanceView;
  75.  
  76. import static com.medicom.organicdrv.utilsLib.ByteArrayToHexString;
  77.  
  78. //import android.util.Base64;
  79.  
  80. public class MainWebView extends AppCompatActivity implements MDDUpdateBalanceView, InitListener, NfcAdapter.ReaderCallback {
  81.     public static final String CALLBACK_DATA = "CALLBACK";
  82.     private int COMMAND = MDDCommand.COMMAND_GET_BALANCE;
  83.     WebView webView;
  84.     protected Context context;
  85.     private InitReader reader;
  86.     private MainCardProcessor cardProcessor;
  87.     private int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
  88.     private String TAG = "MDDService";
  89.     public String status = "getBalance";
  90.     public String cardNumberNow;
  91.     public String exCardNumber;
  92.     public String updateBalanceSuccessInfo;
  93.     public String cardInfo = "6032986092844892";
  94.     boolean hasPendingOperation = false;
  95. //    public String urLCompany = "https://kasirkuweb-dev.multidaya.id/";
  96.         public String urLCompany = "http://192.168.7.169:8000/";
  97.     public String callbackData;
  98.     UpdateBalanceErrorModel ubalError;
  99.     CalbackModel callback;
  100.     List<CalbackModel.itemDetail> detailItem;
  101.     private static String file_type = "image/*";    // file types to be allowed for upload
  102.     private boolean multiple_files = true;         // allowing multiple file upload
  103.     private static final String TAG_WEB = MainWebView.class.getSimpleName();
  104.     private String cam_file_data = null;        // for storing camera file information
  105.     private ValueCallback<Uri> file_data;       // data/header received after file selection
  106.     private ValueCallback<Uri[]> file_path;     // received file(s) temp. location
  107.     private final static int file_req_code = 1;
  108.     private String accessToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJhdXRoLXNlcnZpY2U6MS4wLjAiLCJzdWIiOnsibmFtZSI6IlRlc3RQcm9kMyIsInVzZXJuYW1lIjoiVGVzdFByb2QzIiwiYXV0aF9sZXZlbCI6Ik1FUkNIQU5UIiwibWlkIjoiMWZiNTdmMTY2YTQ4MGU5N2JmN2EzZGNiZjkzMTkyOTMifSwiaWF0IjoxNTk3NzM3NzIxLCJleHAiOjE1OTc4MjQxMjEsIm5iZiI6MTU5NzczNzcyM30.CXM-5mCv91Yo17c9zHXQKPGR5gqAeu-LADta-_qnABYxzmnE4Dx0q7NQ9IYr6cYO6cXp40UW4s632fzVYmPCXH8f0RtSwLPqTT7_lWHK--fHCP-LZOmfgwUBxdNocYY9xAi-NyWqCmTnkjWx91lqh9S9Fcue6nO_KrBqngUpBPhpS0hPwgmkqHXX6yAdVs931NbfNM3cYW9PpGIw8K-OxoPDHByD61uAFxT9FCrTbca7vV3HFQnZEKpwxxdECu7DCQAsGTl7JqfbH2j5swe_t97rSDAGyE1HRzGX-SMqPULkC-XravF2m_HucosacYQuSdRaxAWfEIQvtQhAcRXwTA";
  109.     private LibraryConfig mConfig;
  110.     private Timer timer;
  111.     private String deviceBrand = "";
  112.     private int idxDriver = 0;
  113.  
  114.     @Override
  115.     protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  116.         super.onActivityResult(requestCode, resultCode, intent);
  117.         if (Build.VERSION.SDK_INT >= 21) {
  118.             Uri[] results = null;
  119.  
  120.             /*-- if file request cancelled; exited camera. we need to send null value to make future attempts workable --*/
  121.             if (resultCode == Activity.RESULT_CANCELED) {
  122.                 if (requestCode == file_req_code) {
  123.                     file_path.onReceiveValue(null);
  124.                     return;
  125.                 }
  126.             }
  127.  
  128.             /*-- continue if response is positive --*/
  129.             if (resultCode == Activity.RESULT_OK) {
  130.                 if (requestCode == file_req_code) {
  131.                     if (null == file_path) {
  132.                         return;
  133.                     }
  134.  
  135.                     ClipData clipData;
  136.                     String stringData;
  137.                     try {
  138.                         clipData = intent.getClipData();
  139.                         stringData = intent.getDataString();
  140.                     } catch (Exception e) {
  141.                         clipData = null;
  142.                         stringData = null;
  143.                     }
  144.  
  145.                     if (clipData == null && stringData == null && cam_file_data != null) {
  146.                         results = new Uri[]{Uri.parse(cam_file_data)};
  147.                     } else {
  148.                         if (clipData != null) { // checking if multiple files selected or not
  149.                             final int numSelectedFiles = clipData.getItemCount();
  150.                             results = new Uri[numSelectedFiles];
  151.                             for (int i = 0; i < clipData.getItemCount(); i++) {
  152.                                 results[i] = clipData.getItemAt(i).getUri();
  153.                             }
  154.                         } else {
  155.                             results = new Uri[]{Uri.parse(stringData)};
  156.                         }
  157.                     }
  158.                 }
  159.             }
  160.             file_path.onReceiveValue(results);
  161.             file_path = null;
  162.         } else {
  163.             if (requestCode == file_req_code) {
  164.                 if (null == file_data) return;
  165.                 Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
  166.                 file_data.onReceiveValue(result);
  167.                 file_data = null;
  168.             }
  169.         }
  170.     }
  171.  
  172.     @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
  173.     @Override
  174.     protected void onCreate(Bundle savedInstanceState) {
  175.         super.onCreate(savedInstanceState);
  176.         setContentView(R.layout.activity_main_web_view);
  177.         webView = findViewById(R.id.webViewMain);
  178.         webView.getSettings().setDomStorageEnabled(true);
  179.         webView.getSettings().setLoadsImagesAutomatically(true);
  180.         webView.getSettings().setJavaScriptEnabled(true);
  181.         webView.addJavascriptInterface(new JSBridge(this, cardInfo), "JSBridge");
  182. //        webView.getSettings().setUserAgentString("(Linux; Android SUNMI.P2;) Mobile ");
  183. //        webView.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 5.1.1; Nexus 5 Build/LMY48B; wv) AppleWebKit/537.36 (KHTML, like Gecko)" +
  184. //                " Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36\n");
  185. //        webView.getSettings().setUserAgentString(System.getProperty("http.agent"));
  186.         Log.d("user-agent", ""+System.getProperty("http.agent"));
  187.         webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
  188.         webView.setWebViewClient(new WebViewClient() {
  189.             @Override
  190.             public void onPageFinished(WebView view, String url) {
  191.                 webView.setVisibility(View.VISIBLE);
  192.  
  193.                 if (getSupportActionBar() != null)
  194.                     getSupportActionBar().setTitle("Multidaya Dinamika");
  195.             }
  196.         });
  197.         webView.loadUrl(urLCompany);
  198.         webView.setWebChromeClient(new WebChromeClient() {
  199.             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
  200.  
  201.                 if (file_permission() && Build.VERSION.SDK_INT >= 21) {
  202.                     file_path = filePathCallback;
  203.                     Intent takePictureIntent = null;
  204.                     Intent takeVideoIntent = null;
  205.  
  206.                     boolean includeVideo = false;
  207.                     boolean includePhoto = false;
  208.  
  209.                     /*-- checking the accept parameter to determine which intent(s) to include --*/
  210.                     paramCheck:
  211.                     for (String acceptTypes : fileChooserParams.getAcceptTypes()) {
  212.                         String[] splitTypes = acceptTypes.split(", ?+"); // although it's an array, it still seems to be the whole value; split it out into chunks so that we can detect multiple values
  213.                         for (String acceptType : splitTypes) {
  214.                             switch (acceptType) {
  215.                                 case "*/*":
  216.                                     includePhoto = true;
  217.                                     includeVideo = true;
  218.                                     break paramCheck;
  219.                                 case "image/*":
  220.                                     includePhoto = true;
  221.                                     break;
  222.                                 case "video/*":
  223.                                     includeVideo = true;
  224.                                     break;
  225.                             }
  226.                         }
  227.                     }
  228.  
  229.                     if (fileChooserParams.getAcceptTypes().length == 0) {   //no `accept` parameter was specified, allow both photo and video
  230.                         includePhoto = true;
  231.                         includeVideo = true;
  232.                     }
  233.  
  234.                     if (includePhoto) {
  235.                         takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  236.                         if (takePictureIntent.resolveActivity(MainWebView.this.getPackageManager()) != null) {
  237.                             File photoFile = null;
  238.                             try {
  239.                                 photoFile = create_image();
  240.                                 takePictureIntent.putExtra("PhotoPath", cam_file_data);
  241.                             } catch (IOException ex) {
  242.                                 Log.e(TAG_WEB, "Image file creation failed", ex);
  243.                             }
  244.                             if (photoFile != null) {
  245.                                 cam_file_data = "file:" + photoFile.getAbsolutePath();
  246.                                 takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
  247.                             } else {
  248.                                 cam_file_data = null;
  249.                                 takePictureIntent = null;
  250.                             }
  251.                         }
  252.                     }
  253.  
  254.                     if (includeVideo) {
  255.                         takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
  256.                         if (takeVideoIntent.resolveActivity(MainWebView.this.getPackageManager()) != null) {
  257.                             File videoFile = null;
  258.                             try {
  259.                                 videoFile = create_video();
  260.                             } catch (IOException ex) {
  261.                                 Log.e(TAG_WEB, "Video file creation failed", ex);
  262.                             }
  263.                             if (videoFile != null) {
  264.                                 cam_file_data = "file:" + videoFile.getAbsolutePath();
  265.                                 takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));
  266.                             } else {
  267.                                 cam_file_data = null;
  268.                                 takeVideoIntent = null;
  269.                             }
  270.                         }
  271.                     }
  272.  
  273.                     Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
  274.                     contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
  275.                     contentSelectionIntent.setType(file_type);
  276.                     if (multiple_files) {
  277.                         contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
  278.                     }
  279.  
  280.                     Intent[] intentArray;
  281.                     if (takePictureIntent != null && takeVideoIntent != null) {
  282.                         intentArray = new Intent[]{takePictureIntent, takeVideoIntent};
  283.                     } else if (takePictureIntent != null) {
  284.                         intentArray = new Intent[]{takePictureIntent};
  285.                     } else if (takeVideoIntent != null) {
  286.                         intentArray = new Intent[]{takeVideoIntent};
  287.                     } else {
  288.                         intentArray = new Intent[0];
  289.                     }
  290.  
  291.                     Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
  292.                     chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
  293.                     chooserIntent.putExtra(Intent.EXTRA_TITLE, "File chooser");
  294.                     chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
  295.                     startActivityForResult(chooserIntent, file_req_code);
  296.                     return true;
  297.                 } else {
  298.                     return false;
  299.                 }
  300.             }
  301.         });
  302.     }
  303.  
  304.     public class Callback extends WebViewClient {
  305.         public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
  306.             Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
  307.         }
  308.     }
  309.  
  310.     /*-- checking and asking for required file permissions --*/
  311.     public boolean file_permission() {
  312.         if (Build.VERSION.SDK_INT >= 23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
  313.             ActivityCompat.requestPermissions(MainWebView.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
  314.             return false;
  315.         } else {
  316.             return true;
  317.         }
  318.     }
  319.  
  320.     /*-- creating new image file here --*/
  321.     private File create_image() throws IOException {
  322.         @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
  323.         String imageFileName = "img_" + timeStamp + "_";
  324.         File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
  325.         return File.createTempFile(imageFileName, ".jpg", storageDir);
  326.     }
  327.  
  328.     /*-- creating new video file here --*/
  329.     private File create_video() throws IOException {
  330.         @SuppressLint("SimpleDateFormat")
  331.         String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
  332.         String new_name = "file_" + file_name + "_";
  333.         File sd_directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
  334.         return File.createTempFile(new_name, ".3gp", sd_directory);
  335.     }
  336.  
  337.     /*-- back/down key handling --*/
  338.     @Override
  339.     public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
  340.         if (event.getAction() == KeyEvent.ACTION_DOWN) {
  341.             if (keyCode == KeyEvent.KEYCODE_BACK) {
  342.                 if (webView.canGoBack()) {
  343.                     webView.goBack();
  344.                 } else {
  345.                     finish();
  346.                 }
  347.                 return true;
  348.             }
  349.         }
  350.         return super.onKeyDown(keyCode, event);
  351.     }
  352.  
  353.     @Override
  354.     public void onConfigurationChanged(Configuration newConfig) {
  355.         super.onConfigurationChanged(newConfig);
  356.     }
  357.  
  358.     public void checkNfc() {
  359. //        if (isInternetAvailable()) {
  360.         NfcManager manager = (NfcManager) getSystemService(Context.NFC_SERVICE);
  361.         NfcAdapter adapter = manager.getDefaultAdapter();
  362.         Log.d(TAG, "adapter:" + adapter + "," + Build.MODEL + "," + Build.BRAND);
  363.         Tag tagFromIntent = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
  364.         if (tagFromIntent != null) {
  365.             onTagDiscovered(tagFromIntent);
  366.         }
  367.         if (adapter == null || !adapter.isEnabled()) {
  368.             runOnUiThread(() -> {
  369.                 webView.evaluateJavascript("javascript: " + "ifNfcFound(\"" + "false" + "\")", null);
  370.                 webView.evaluateJavascript("javascript: " + "getBrand(\"" + deviceBrand + "\")", null);
  371.                 Log.d("brand", deviceBrand);
  372.             });
  373.         } else {
  374.             runOnUiThread(() -> {
  375.                 webView.evaluateJavascript("javascript: " + "ifNfcFound(\"" + "true" + "\")", null);
  376.                 validateHasPermissions();
  377.             });
  378.         }
  379.  
  380.         String imei = Settings.Secure.getString(getContentResolver(), "android_id");
  381.         Log.e("imei", imei);
  382. //        }
  383.     }
  384.  
  385.     private void validateHasPermissions() {
  386.         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  387.         StrictMode.setThreadPolicy(policy);
  388.  
  389.         // permission READ_PHONE_STATE
  390.         if (ContextCompat.checkSelfPermission(this,
  391.                 Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
  392.             Toast.makeText(this, "Please grant permission", Toast.LENGTH_SHORT).show();
  393.             if (ActivityCompat.shouldShowRequestPermissionRationale(this,
  394.                     Manifest.permission.READ_PHONE_STATE)) {
  395.             } else {
  396.                 ActivityCompat.requestPermissions(this,
  397.                         new String[]{Manifest.permission.READ_PHONE_STATE,
  398.                                 Manifest.permission.INTERNET,
  399.                                 Manifest.permission.READ_EXTERNAL_STORAGE},
  400.                         MY_PERMISSIONS_REQUEST_READ_CONTACTS);
  401.             }
  402.  
  403.         } else {
  404.             Log.d("validate", "Mau init niih");
  405.             if (!deviceBrand.equalsIgnoreCase("sunmi"))
  406.                 ((TradeApplication) getApplication()).initAar(this);
  407.             else {
  408.                 AarDeviceId aarDeviceId = new AarDeviceId(this);
  409.                 try {
  410.                     aarDeviceId.getDeviceId();
  411.                 } catch (DeviceNotRegisteredException e) {
  412.                     aarDeviceId.init(accessToken, DeviceEnvironment.PROD);
  413.                 }
  414.  
  415.                 try {
  416.                     mConfig = new LibraryConfig(
  417.                             "ba7db816e59612f8ce1630a095ef01c5",
  418.                             aarDeviceId.getDeviceId(),
  419.                             "5b423ef49cb029340d7231cace0de201",
  420.                             accessToken,
  421.                             1
  422.                     );
  423.                 } catch (DeviceNotRegisteredException e) {
  424.                     e.printStackTrace();
  425.                 }
  426.  
  427.                 final nativeLib[] nativeLibrary = new nativeLib[1];
  428.                 InitDebugCertificate initDebugCertificate = new InitDebugCertificate();
  429.                 AsyncTask.execute(new Runnable() {
  430.                     @Override
  431.                     public void run() {
  432.                         try {
  433.                             nativeLibrary[0] = new nativeLib(getApplicationContext(), idxDriver);
  434.                             reader = initDebugCertificate.getDebug(nativeLibrary[0], getApplicationContext(), idxDriver, mConfig, true);
  435.                             onInitReaderComplete(reader);
  436.                         } catch (Exception e) {
  437.                             e.printStackTrace();
  438.                         }
  439.                     }
  440.                 });
  441.             }//            execute(null);
  442. //            cardProcessor.getBalance();
  443.         }
  444.     }
  445.  
  446.     @Override
  447.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  448.         super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  449.         Log.e("requestPermissionResult", "reqCode " + requestCode + " permission " + permissions + " grantResults " + grantResults);
  450. //        ((TradeApplication) getApplication()).initAar(this);
  451.     }
  452.  
  453.     @Override
  454.     protected void onResume() {
  455.         Log.e("onResume", "onresume");
  456.         super.onResume();
  457.  
  458.         deviceBrand = Build.BRAND;
  459.         Log.d("Brand", deviceBrand);
  460.         if (deviceBrand.equalsIgnoreCase("sunmi")) {
  461.             idxDriver = nativeLib.USE_SunMi_ENGGINE;
  462.             validateHasPermissions();
  463.         } else
  464.             checkNfc();
  465.     }
  466.  
  467.     private void setCommand(int commandUpdateBalance) {
  468.         COMMAND = commandUpdateBalance;
  469. //        btnUpdateBalance.setText(COMMAND == MDDCommand.COMMAND_UPDATE_BALANCE ? "Update Balance" : "Cek Balance");
  470.     }
  471.  
  472.     @Override
  473.     protected void onPause() {
  474.         super.onPause();
  475.         NfcManager manager = (NfcManager) getSystemService(Context.NFC_SERVICE);
  476.         NfcAdapter adapter = manager.getDefaultAdapter();
  477.         if (adapter != null && adapter.isEnabled()) {
  478.             adapter.disableReaderMode(this);
  479.         }
  480.     }
  481.  
  482.     @Override
  483.     public void onTagDiscovered(Tag tag) {
  484.         execute(tag);
  485.     }
  486.  
  487.     @Override
  488.     public void onInitReaderComplete(InitReader reader) {
  489.         this.reader = reader;
  490.         if (!deviceBrand.equalsIgnoreCase("sunmi"))
  491.             enableReaderMode();
  492.  
  493.         cardProcessor = new MainCardProcessor(MainWebView.this, reader, new UpdateBalanceView() {
  494.             @Override
  495.             public void onUpdateBalanceSuccess(SuccessUpdateBalance successUpdateBalance) {
  496.                 runOnUiThread(() -> MainWebView.this.onUpdateBalaceSuccess(successUpdateBalance));
  497.             }
  498.  
  499.             @Override
  500.             public void onUpdateBalanceError(String reason) {
  501.                 runOnUiThread(() -> MainWebView.this.onUpdateBalanceError(reason));
  502.             }
  503.  
  504.             @Override
  505.             public void onCardDetected(CardInfo cardInfo) {
  506.                 runOnUiThread(() -> MainWebView.this.onBalanceInfoAvailable(cardInfo));
  507.             }
  508.  
  509.             @Override
  510.             public void onErrorNfcCardMsg(int errorCode) {
  511.                 runOnUiThread(() -> MainWebView.this.onUpdateBalanceError(""));
  512.             }
  513.         }, ApiUtils.prod_environment);
  514.  
  515. //        if (deviceBrand.equalsIgnoreCase("sunmi")) {
  516. //            timer = new Timer();
  517. //            timer.schedule(new TimerTask() {
  518. //                @Override
  519. //                public void run() {
  520. //                    execute(null);
  521. //                }
  522. //            }, 0, 5000);
  523. //        }
  524.  
  525.     }
  526.  
  527.     @Override
  528.     public void onNFcCardNotSupported(int i) {
  529.         hasPendingOperation = false;
  530.     }
  531.  
  532.     @Override
  533.     public void onNfcCardFound() {
  534.         hasPendingOperation = true;
  535.         runOnUiThread(this::sendCardDetected);
  536.     }
  537.  
  538.     @Override
  539.     public void onFinishOperation() {
  540.         hasPendingOperation = false;
  541.     }
  542.  
  543.     @Override
  544.     public void onBalanceInfoAvailable(CardInfo cardInfo1) {
  545.         hasPendingOperation = false;
  546. //
  547. //        if (deviceBrand.equalsIgnoreCase("sunmi")) {
  548. //            timer = new Timer();
  549. //            timer.schedule(new TimerTask() {
  550. //                @Override
  551. //                public void run() {
  552. //                    execute(null);
  553. //                }
  554. //            }, 0, 5000);
  555. //        }
  556.  
  557. //        cardInfo = new Gson().toJson(cardInfo1);
  558. //        runOnUiThread(MainWebView.this::sendCardNumber, sendCardBalance);
  559. //        runOnUiThread(this::sendCardInfo);
  560.         Log.d("CardInfoBoy", cardInfo);
  561.     }
  562.  
  563.     @Override
  564.     public void onUpdateBalaceSuccess(SuccessUpdateBalance successUpdateBalance) {
  565.         updateBalanceSuccessInfo = new Gson().toJson(successUpdateBalance);
  566.             runOnUiThread(this::sendUbal);
  567.         status = "getBalance";
  568.         Log.d("status_sekarang", status);
  569.         Log.d("updatesuccesscoyy", updateBalanceSuccessInfo);
  570.     }
  571.  
  572.     @Override
  573.     public void onUpdateBalanceError(String s) {
  574.         status = "getBalance";
  575.         ubalError = new UpdateBalanceErrorModel();
  576.         ubalError.setCardNumber(cardNumberNow);
  577.         ubalError.setMessage(s);
  578.         runOnUiThread(this::sendUbalError);
  579.         Log.d("ubalError", s);
  580.     }
  581.  
  582.     @Override
  583.     public void onBeginOperation() {
  584.         hasPendingOperation = true;
  585.         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  586.     }
  587.  
  588.     public class JSBridge {
  589.         Context context;
  590.         String data;
  591.  
  592.         public JSBridge(Context context, String data) {
  593.             this.context = context;
  594.             this.data = data;
  595.         }
  596.  
  597.         @JavascriptInterface
  598.         public void printReceipt(String message) throws Exception {
  599.             callbackData = message;
  600.             Log.d("yg diprint", callbackData);
  601.             callback = new Gson().fromJson(callbackData, CalbackModel.class);
  602.             detailItem = callback.getItemDetail();
  603.             Bitmap bitmap = ReceiptFactory.getPOSReceipt(context, callback, detailItem);
  604.             DevicePrinter.printReceipt(context, bitmap);
  605.  
  606.             runOnUiThread(() -> {
  607.                 webView.evaluateJavascript("javascript: " + "successPrint(\"" + "" + "\")", null);
  608.             });
  609.         }
  610.  
  611.         @JavascriptInterface
  612.         public void sendCardNumber(String cardNumber) {
  613.             exCardNumber = cardNumber;
  614.             Log.d("CardNumberDariWeb", exCardNumber);
  615.             Log.d("CardNumberSekarang", cardNumberNow);
  616.         }
  617.         @JavascriptInterface
  618.         public void executeSunmi(){
  619. //            runOnUiThread(MainWebView.this::getCardNumberinSunmi);
  620.             runOnUiThread(()->{
  621.                 MainWebView.this.execute(null);
  622.             });
  623.         }
  624.         @JavascriptInterface
  625.         public void isNfcFound() {
  626.             runOnUiThread(MainWebView.this::checkNfc);
  627.         }
  628.  
  629.         @JavascriptInterface
  630.         public void getStatus(String message) {
  631.             status = message;
  632. //
  633. //            if (deviceBrand.equalsIgnoreCase("sunmi")) {
  634. //                timer = new Timer();
  635. //                timer.schedule(new TimerTask() {
  636. //                    @Override
  637. //                    public void run() {
  638. //                        execute(null);
  639. //                    }
  640. //                }, 0, 5000);
  641. //            }
  642.             Log.d("status_dari_web", status);
  643.         }
  644.     }
  645.  
  646.     public void sendCardDetected() {
  647.         String scriptCardDetected = "javascript:cardDetected('cardDetected')";
  648.         webView.evaluateJavascript(scriptCardDetected, null);
  649.     }
  650.  
  651.     public void sendUbalError() {
  652.         String scriptUbal = "javascript:updateBalance('%s')";
  653.         String sendError = new Gson().toJson(ubalError);
  654.         Log.d("ubalError", sendError);
  655.         String dataUbal = Base64.encodeToString(sendError.getBytes(), Base64.DEFAULT);
  656.         dataUbal = dataUbal.replace("\n", "");
  657.         String sendData = String.format(scriptUbal, dataUbal);
  658.         webView.evaluateJavascript(sendData, null);
  659.     }
  660.  
  661.     public void sendUbal() {
  662.         String scriptUbal = "javascript:updateBalance('%s')";
  663.         String dataUbal = Base64.encodeToString(updateBalanceSuccessInfo.getBytes(), Base64.DEFAULT);
  664.         dataUbal = dataUbal.replace("\n", "");
  665.         String sendData = String.format(scriptUbal, dataUbal);
  666.         webView.evaluateJavascript(sendData, null);
  667.     }
  668.  
  669.     public void getCardNumber() {
  670.         String scriptCardInfo = "javascript:setCard('%s')";
  671.         Log.d("kirimwebcardinfo", cardInfo);
  672.         String dataCard = Base64.encodeToString(cardInfo.getBytes(), Base64.DEFAULT);
  673. //        try {
  674. //            String dataCard2 = EncryptLib.encrypt(context, cardInfo, "");
  675. //        }catch (Exception e) {
  676. //            e.printStackTrace();
  677. //        }
  678.         dataCard = dataCard.replace("\n", "");
  679.         Log.d("kirimwebcardstring", dataCard);
  680.         String sendCard = String.format(scriptCardInfo, dataCard);
  681.         Log.d("kirimweb", sendCard);
  682.         webView.evaluateJavascript(sendCard, null);
  683.     }
  684.     public void getCardNumberinSunmi() {
  685.         execute(null);
  686.         String scriptCardInfo = "javascript:setCard('%s')";
  687.         Log.d("kirimwebcardinfo", cardInfo);
  688.         String dataCard = Base64.encodeToString(cardInfo.getBytes(), Base64.DEFAULT);
  689. //        try {
  690. //            String dataCard2 = EncryptLib.encrypt(context, cardInfo, "");
  691. //        }catch (Exception e) {
  692. //            e.printStackTrace();
  693. //        }
  694.         dataCard = dataCard.replace("\n", "");
  695.         Log.d("kirimwebcardstring", dataCard);
  696.         String sendCard = String.format(scriptCardInfo, dataCard);
  697.         Log.d("kirimweb", sendCard);
  698.         webView.evaluateJavascript(sendCard, null);
  699.     }
  700.     private void execute(Tag tag) {
  701.         Log.d("Execute", "execute dipanggil");
  702.         if (reader != null) {
  703.             if (!deviceBrand.equalsIgnoreCase("sunmi")) {
  704.                 cardProcessor.lockIsoDepCard(tag);
  705.                 String cardUid = ByteArrayToHexString(tag.getId());
  706.                 Log.d("TagFromIntent", cardUid);
  707.                 boolean hasCardUid = !cardUid.isEmpty();
  708.                 if (hasCardUid) {
  709.                     Log.d(TAG, "---> Send to UI Card Found");
  710.                     runOnUiThread(() -> onNfcCardFound());
  711.  
  712.                     CardInfoCommand command = new CardInfoCommand(reader.myReader);
  713.                     Log.e("myReader", "Myreader : " + reader.myReader);
  714.  
  715.                     final CommandResult<CardInfo> execute = command.execute(cardUid);
  716.                     CardInfo detectedCardInfo = execute.getResult();
  717.                     Log.d("cardInfo", "ini card infonnya bro : " + detectedCardInfo.toString());
  718.                     Log.d("executeSuccess", "executeIsSuccess = " + execute.isSuccess());
  719.                     if (execute.isSuccess()) {
  720.                         cardNumberNow = detectedCardInfo.getCardNumber();
  721.                         cardInfo = new Gson().toJson(detectedCardInfo);
  722.                         runOnUiThread(this::getCardNumber);
  723.                         if (detectedCardInfo.getBankType().toLowerCase().contains("dki")
  724.                                 || detectedCardInfo.getBankType().toLowerCase().contains("bca")) {
  725.                             runOnUiThread(() -> {
  726.                                 MainWebView.this.onBalanceInfoAvailable(detectedCardInfo);
  727.                             });
  728.                         } else {
  729.                             if (exCardNumber != null) {
  730.                                 if (!exCardNumber.equalsIgnoreCase(detectedCardInfo.getCardNumber())) {
  731.                                     Log.d("cardsekarang", detectedCardInfo.getCardNumber());
  732.                                     runOnUiThread(() -> {
  733.                                         webView.evaluateJavascript("javascript: " + "ifCardNotSame(\"" + "" + "\")", null);
  734.                                     });
  735.                                 } else {
  736.                                     cardProcessor.updateBalance(detectedCardInfo, 1, null);
  737. //                                    runOnUiThread(this::sendUbal);
  738.                                 }
  739.                             }
  740.                             if (status.equals("updateBalance")) {
  741. //                            cardProcessor.getBalance(detectedCardInfo);
  742.                                 cardProcessor.updateBalance(detectedCardInfo, 1, null);
  743.                             } else {
  744.                                 cardProcessor.getBalance(detectedCardInfo, null);
  745.                             }
  746.                         }
  747.                     } else {
  748.                         runOnUiThread(() -> {
  749.                             Log.e("error", "Messagenya : " + execute.getMessage());
  750.                             MainWebView.this.onUpdateBalanceError("Kartu tidak terdeteksi");
  751.                             cardProcessor.unlockIsoDepCard();
  752.                         });
  753.                     }
  754.                     cardProcessor.unlockIsoDepCard();
  755.  
  756.                 } else {
  757.                     //wrong card type
  758.                     cardProcessor.unlockIsoDepCard();
  759.                 }
  760.             } else {
  761. //                cardProcessor.getBalance();
  762.                 String cardUid = cardProcessor.findCardUid();
  763.                 Log.d("TagFromIntent", cardUid);
  764.                 boolean hasCardUid = !cardUid.isEmpty();
  765.                 if (hasCardUid) {
  766.                     Log.d(TAG, "---> Send to UI Card Found");
  767.                     runOnUiThread(this::onNfcCardFound);
  768. //                    timer.cancel();
  769.                     CardInfoCommand command = new CardInfoCommand(reader.myReader);
  770.                     Log.e("myReader", "Myreader : " + reader.myReader);
  771.  
  772.                     final CommandResult<CardInfo> execute = command.execute(cardUid);
  773.                     CardInfo detectedCardInfo = execute.getResult();
  774. //                    Log.d("cardInfo", "ini card infonnya bro : " + detectedCardInfo.toString());
  775.                     Log.d("executeSuccess", "executeIsSuccess = " + execute.isSuccess());
  776.  
  777.                     if (execute.isSuccess()) {
  778.                         cardNumberNow = detectedCardInfo.getCardNumber();
  779.                         cardInfo = new Gson().toJson(detectedCardInfo);
  780.                         runOnUiThread(this::getCardNumber);
  781.                         if (detectedCardInfo.getBankType().toLowerCase().contains("dki")
  782.                                 || detectedCardInfo.getBankType().toLowerCase().contains("bca")) {
  783.                             runOnUiThread(() -> {
  784.                                 MainWebView.this.onBalanceInfoAvailable(detectedCardInfo);
  785.                             });
  786.                         } else {
  787.                             if (status.equals("updateBalance")) {
  788. //                            cardProcessor.getBalance(detectedCardInfo);
  789.                                 cardProcessor.updateBalance(detectedCardInfo, 1, null);
  790.                             } else {
  791.                                 cardProcessor.getBalance(detectedCardInfo, null);
  792.                             }
  793.                         }
  794.                     } else {
  795.                         runOnUiThread(() -> {
  796.                             Log.e("error", "Messagenya : " + execute.getMessage());
  797.                             MainWebView.this.onUpdateBalanceError("Kartu tidak terdeteksi");
  798.                         });
  799.                     }
  800.                 }
  801.             }
  802.         }
  803.     }
  804.  
  805.     public boolean isInternetAvailable() {
  806.         try {
  807.             InetAddress ipAddr = InetAddress.getByName("google.com");
  808.             return !ipAddr.equals("");
  809.         } catch (Exception e) {
  810.             return false;
  811.         }
  812.     }
  813.  
  814.     private void enableReaderMode() {
  815.         // Recommend NfcAdapter flags for reading from other Android devices. Indicates that this
  816.         // activity is interested in NFC-A devices (including other Android devices), and that the
  817.         // system should not check for the presence of NDEF-formatted data (e.g. Android Beam).
  818.         //final int READER_FLAGS = NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_NFC_B | NfcAdapter.FLAG_READER_NFC_F | NfcAdapter.FLAG_READER_NFC_V | NfcAdapter.FLAG_READER_NFC_BARCODE | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK;
  819.         final int READER_FLAGS = NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK;
  820.         ;
  821.         NfcAdapter nfc = NfcAdapter.getDefaultAdapter(this);
  822.         if (nfc != null && nfc.isEnabled()) {
  823.             nfc.enableReaderMode(this, this, READER_FLAGS, null);
  824.             Log.i(TAG, "Enabling reader mode");
  825.         }
  826.  
  827.     }
  828. }
Add Comment
Please, Sign In to add comment