const onResult = function(args) {
            const requestCode = args.requestCode;
            const resultCode = args.resultCode;
            const data = args.intent;
            // var _that = this;

            if (resultCode === android.app.Activity.RESULT_OK && requestCode === com.yalantis.ucrop.UCrop.REQUEST_CROP) {
              const resultUri: android.net.Uri = com.yalantis.ucrop.UCrop.getOutput(data);
              const is: ImageSource = new ImageSource();
              try {
                is.setNativeSource(android.graphics.BitmapFactory.decodeFile(resultUri.getPath()));
              } catch (e) {
                console.error(e);
              }
              ImageCropper._cleanFiles();
              application.android.off(application.AndroidApplication.activityResultEvent, onResult);
              if (is.android) {
                resolve({
                  response: "Success",
                  image: is,
                });
              } else {
                reject({
                  response: "Error",
                  image: null
                });
              }
              return;
            }
            else if (resultCode === android.app.Activity.RESULT_CANCELED && requestCode === com.yalantis.ucrop.UCrop.REQUEST_CROP) {
              ImageCropper._cleanFiles();
              application.android.off(application.AndroidApplication.activityResultEvent, onResult);
              resolve({
                response: "Cancelled",
                image: null
              });
              return;
            }
            else if (resultCode === com.yalantis.ucrop.UCrop.RESULT_ERROR) {
              ImageCropper._cleanFiles();
              const cropError: java.lang.Throwable = com.yalantis.ucrop.UCrop.getError(data);
              console.log(cropError.getMessage());
              application.android.off(application.AndroidApplication.activityResultEvent, onResult);
              reject({
                response: "Error",
                image: null
              });
              return;
            }
          };
export function onUnloaded(args) {
    console.log("back-button modal test unloaded");

    if (androidApp) {
        androidApp.off("activityBackPressed", activityBackPressedCallback);
    }
}
        app.android.on(app.AndroidApplication.activityRequestPermissionsEvent, (args: app.AndroidActivityRequestPermissionsEventData) => {
            if (permissions.hasPermission((android as any).Manifest.permission.CAMERA) && permissions.hasPermission((android as any).Manifest.permission.RECORD_AUDIO)) {
                this.startPreview();
                app.android.off(app.AndroidApplication.activityRequestPermissionsEvent);
            }

        });
 public onUnloaded(): void {
     if (this.nativeView && this.nativeView.release) {
         this.nativeView.release();
     }
     app.android.off(app.AndroidApplication.activityRequestPermissionsEvent);
     super.onUnloaded();
 }
    public createNativeView() {
        app.android.on(app.AndroidApplication.activityRequestPermissionsEvent, (args: app.AndroidActivityRequestPermissionsEventData) => {
            if (permissions.hasPermission((android as any).Manifest.permission.CAMERA) && permissions.hasPermission((android as any).Manifest.permission.RECORD_AUDIO)) {
                this.startPreview();
                app.android.off(app.AndroidApplication.activityRequestPermissionsEvent);
            }

        });
        return new co.fitcom.fancycamera.FancyCamera(this._context);
    }
export function onLoaded(args) {
    console.log("back-button modal test loaded");
    context = fromObject({
        message: "First back-press will be canceled",
        shouldCancel: true
    });

    args.object.bindingContext = context;

    if (androidApp) {
        androidApp.on("activityBackPressed", activityBackPressedCallback);
    }
}
 const onActivityResult = (data: AndroidActivityResultEventData) => {
   if (data.requestCode === REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS) {
     if (data.resultCode === android.app.Activity.RESULT_OK) { // OK = -1
       // the user has just authenticated via the ConfirmDeviceCredential activity
       resolve();
     } else {
       // the user has quit the activity without providing credentials
       reject({
         code: ERROR_CODES.USER_CANCELLED,
         message: "User cancelled."
       });
     }
   }
   app.android.off(app.AndroidApplication.activityResultEvent, onActivityResult);
 };
    return new Promise((resolve, reject) => {
      try {
        // in case 'activity.getSupportFragmentManager' is available ({N} started supporting it,
        // or the user added our Activity to their Android manifest), use the 3rd party FP library
        const hasSupportFragment = this.getActivity().getSupportFragmentManager !== undefined;

        if (options.useCustomAndroidUI && !hasSupportFragment) {
          reject({
            code: ERROR_CODES.DEVELOPER_ERROR,
            message: "Custom Fingerprint UI requires changes to AndroidManifest.xml. See the nativescript-fingerprint-auth documentation."
          });

        } else if (options.useCustomAndroidUI && hasSupportFragment) {
          if (!this.fingerPrintManager) {
            this.fingerPrintManager = new com.jesusm.kfingerprintmanager.KFingerprintManager(utils.ad.getApplicationContext(), KEY_NAME);
          }
          const that = this;
          const callback = new com.jesusm.kfingerprintmanager.KFingerprintManager.AuthenticationCallback({
            attempts: 0,
            onAuthenticationFailedWithHelp(help): void {
              if (++this.attempts < 3) {
                // just invoke the UI again as it's very sensitive (need a timeout to prevent an infinite loop)
                setTimeout(() => that.verifyWithCustomAndroidUI(resolve, reject, this), 50);
              } else {
                reject({
                  code: ERROR_CODES.RECOVERABLE_ERROR,
                  message: help
                });
              }
            },
            onAuthenticationSuccess(): void {
              resolve();
            },
            onSuccessWithManualPassword(password): void {
              resolve(password);
            },
            onFingerprintNotRecognized(): void {
              if (++this.attempts < 3) {
                // just invoke the UI again as it's very sensitive (need a timeout to prevent an infinite loop)
                setTimeout(() => that.verifyWithCustomAndroidUI(resolve, reject, this), 50);
              } else {
                reject({
                  code: ERROR_CODES.NOT_RECOGNIZED,
                  message: "Fingerprint not recognized."
                });
              }
            },
            onFingerprintNotAvailable(): void {
              reject({
                code: ERROR_CODES.NOT_CONFIGURED,
                message: "Secure lock screen hasn't been set up.\n Go to \"Settings -> Security -> Screenlock\" to set up a lock screen."
              });
            },
            onCancelled(): void {
              reject({
                code: ERROR_CODES.PASSWORD_FALLBACK_SELECTED,
                message: "Cancelled by user"
              });
            }
          });
          this.verifyWithCustomAndroidUI(resolve, reject, callback);

        } else {

          const onActivityResult = (data: AndroidActivityResultEventData) => {
            if (data.requestCode === REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS) {
              if (data.resultCode === android.app.Activity.RESULT_OK) { // OK = -1
                // the user has just authenticated via the ConfirmDeviceCredential activity
                resolve();
              } else {
                // the user has quit the activity without providing credentials
                reject({
                  code: ERROR_CODES.USER_CANCELLED,
                  message: "User cancelled."
                });
              }
            }
            app.android.off(app.AndroidApplication.activityResultEvent, onActivityResult);
          };

          app.android.on(app.AndroidApplication.activityResultEvent, onActivityResult);

          if (!this.keyguardManager) {
            reject({
              code: ERROR_CODES.NOT_AVAILABLE,
              message: "Keyguard manager not available."
            });
          }
          if (this.keyguardManager && !this.keyguardManager.isKeyguardSecure()) {
            reject({
              code: ERROR_CODES.NOT_CONFIGURED,
              message: "Secure lock screen hasn't been set up.\n Go to \"Settings -> Security -> Screenlock\" to set up a lock screen."
            });
          }

          FingerprintAuth.createKey(options);

          const tryEncryptResult: boolean = this.tryEncrypt(options);
          if (tryEncryptResult === undefined) {
            // this one is async
          } else if (tryEncryptResult === true) {
            resolve();
          } else {
            reject({
              code: ERROR_CODES.UNEXPECTED_ERROR,
              message: "See the console for error logs."
            });
          }
        }
      } catch (ex) {
        console.log(`Error in fingerprint-auth.verifyFingerprint: ${ex}`);
        reject({
          code: ERROR_CODES.UNEXPECTED_ERROR,
          message: ex
        });
      }
    });
var dir = context.getFilesDir();
// << application-app-android-context

// >> application-app-android-current
if (androidApp.foregroundActivity === androidApp.startActivity) {
    ////console.log("We are currently in the main (start) activity of the application");
}
// << application-app-android-current

// >> application-app-android-broadcast
//// Register the broadcast receiver
if (app.android) {
    app.android.registerBroadcastReceiver(android.content.Intent.ACTION_BATTERY_CHANGED,
        function onReceiveCallback(context: android.content.Context, intent: android.content.Intent) {
            var level = intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
            var scale = intent.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1);
            var percent = (level / scale) * 100.0;
            ////console.log("Battery: " + percent + "%");
        });
}
//// When no longer needed, unregister the broadcast receiver
if (app.android) {
    app.android.unregisterBroadcastReceiver(android.content.Intent.ACTION_BATTERY_CHANGED);
}
// << application-app-android-broadcast

export var testAndroidApplicationInitialized = function () {
    TKUnit.assert(app.android, "Android application not initialized.");
    TKUnit.assert(app.android.context, "Android context not initialized.");
    TKUnit.assert(app.android.currentContext, "Android currentContext not initialized.");
    TKUnit.assert(app.android.foregroundActivity, "Android foregroundActivity not initialized.");
    return new Promise<Result>((resolve: (val: Result) => void, reject: (val: Result) => void) => {
      try {
        _options = options;
        if (image.android) {
          const sourcePathTemp: string = ImageCropper._storeImageSource(image);
          const folder: fs.Folder = fs.knownFolders.temp();
          const destinationPathTemp: string = fs.path.join(folder.path, "destTemp.jpeg");
          if (sourcePathTemp == null) {
            ImageCropper._cleanFiles();
            reject({
              response: "Error",
              image: null
            });
          }

          const sourcePath: android.net.Uri = android.net.Uri.parse("file://" + sourcePathTemp); // Fix our path that comes from {N} file-system.
          const destinationPath: android.net.Uri = android.net.Uri.parse("file://" + destinationPathTemp); // Fix our path that comes from {N} file-system.

          const onResult = function(args) {
            const requestCode = args.requestCode;
            const resultCode = args.resultCode;
            const data = args.intent;
            // var _that = this;

            if (resultCode === android.app.Activity.RESULT_OK && requestCode === com.yalantis.ucrop.UCrop.REQUEST_CROP) {
              const resultUri: android.net.Uri = com.yalantis.ucrop.UCrop.getOutput(data);
              const is: ImageSource = new ImageSource();
              try {
                is.setNativeSource(android.graphics.BitmapFactory.decodeFile(resultUri.getPath()));
              } catch (e) {
                console.error(e);
              }
              ImageCropper._cleanFiles();
              application.android.off(application.AndroidApplication.activityResultEvent, onResult);
              if (is.android) {
                resolve({
                  response: "Success",
                  image: is,
                });
              } else {
                reject({
                  response: "Error",
                  image: null
                });
              }
              return;
            }
            else if (resultCode === android.app.Activity.RESULT_CANCELED && requestCode === com.yalantis.ucrop.UCrop.REQUEST_CROP) {
              ImageCropper._cleanFiles();
              application.android.off(application.AndroidApplication.activityResultEvent, onResult);
              resolve({
                response: "Cancelled",
                image: null
              });
              return;
            }
            else if (resultCode === com.yalantis.ucrop.UCrop.RESULT_ERROR) {
              ImageCropper._cleanFiles();
              const cropError: java.lang.Throwable = com.yalantis.ucrop.UCrop.getError(data);
              console.log(cropError.getMessage());
              application.android.off(application.AndroidApplication.activityResultEvent, onResult);
              reject({
                response: "Error",
                image: null
              });
              return;
            }
          };

          application.android.on(application.AndroidApplication.activityResultEvent, onResult);

          if (_options && _options.width && _options.height) {
            const gcd = ImageCropper._gcd(_options.width, _options.height);
            // console.log("gcd:" + gcd.toString());

            com.yalantis.ucrop.UCrop.of(sourcePath, destinationPath)
              .withAspectRatio(_options.width / gcd, _options.height / gcd)
              .withMaxResultSize(_options.width, _options.height)
              .start(ImageCropper._getContext());
          }
          else {
            com.yalantis.ucrop.UCrop.of(sourcePath, destinationPath)
              // .useSourceImageAspectRatio()
              .start(ImageCropper._getContext());
          }
        }
        else {
          // application.android.off(application.AndroidApplication.activityResultEvent, this.onResult);
          reject({
            response: "Error",
            image: null
          });
        }
      } catch (e) {
        // application.android.off(application.AndroidApplication.activityResultEvent, this.onResult);
        reject({
          response: "Error",
          image: null
        });
      }
    });