com.getcapacitor.JSObject Java Examples

The following examples show how to use com.getcapacitor.JSObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleProviderHandler.java    From capacitor-firebase-auth with MIT License 7 votes vote down vote up
@Override
public void fillResult(AuthCredential credential, JSObject jsResult) {
    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this.plugin.getContext());
    if (account != null)  {
        jsResult.put("idToken", account.getIdToken());
    } else {
        Log.w(GOOGLE_TAG, "Ops, there was not last signed in account on google api.");
    }
}
 
Example #2
Source File: StatusBar.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void getInfo(final PluginCall call) {
  View decorView = getActivity().getWindow().getDecorView();
  Window window = getActivity().getWindow();

  String style;
  if ((decorView.getSystemUiVisibility() & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) == View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) {
    style = "LIGHT";
  } else {
    style = "DARK";
  }

  JSObject data = new JSObject();
  data.put("visible", (decorView.getSystemUiVisibility() & View.SYSTEM_UI_FLAG_FULLSCREEN) != View.SYSTEM_UI_FLAG_FULLSCREEN);
  data.put("style", style);
  data.put("color", String.format("#%06X", (0xFFFFFF & window.getStatusBarColor())));
  call.resolve(data);
}
 
Example #3
Source File: AdmobPlus.java    From admob-plus with MIT License 6 votes vote down vote up
@PluginMethod()
public void interstitial_isLoaded(final PluginCall call) {
    Ad ad = getAdOrRejectMissing(call);
    if (ad == null) {
        return;
    }
    final Interstitial interstitial = (Interstitial) ad;
    bridge.executeOnMainThread(new Runnable() {
        @Override
        public void run() {
            final JSObject result = new JSObject();
            result.put("isLoaded", interstitial.isLoaded());
            call.resolve(result);
        }
    });
}
 
Example #4
Source File: Device.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void getInfo(PluginCall call) {
  JSObject r = new JSObject();

  r.put("memUsed", getMemUsed());
  r.put("diskFree", getDiskFree());
  r.put("diskTotal", getDiskTotal());
  r.put("model", android.os.Build.MODEL);
  r.put("osVersion", android.os.Build.VERSION.RELEASE);
  r.put("appVersion", getAppVersion());
  r.put("platform", getPlatform());
  r.put("manufacturer", android.os.Build.MANUFACTURER);
  r.put("uuid", getUuid());
  r.put("batteryLevel", getBatteryLevel());
  r.put("isCharging", isCharging());
  r.put("isVirtual", isVirtual());

  call.success(r);
}
 
Example #5
Source File: PushNotifications.java    From OsmGo with MIT License 6 votes vote down vote up
@Override
protected void handleOnNewIntent(Intent data) {
  super.handleOnNewIntent(data);
  Bundle bundle = data.getExtras();
  if(bundle != null && bundle.containsKey("google.message_id")) {
    JSObject notificationJson = new JSObject();
    JSObject dataObject = new JSObject();
    for (String key : bundle.keySet()) {
      if (key.equals("google.message_id")) {
        notificationJson.put("id", bundle.get(key));
      } else {
        Object value = bundle.get(key);
        String valueStr = (value != null) ? value.toString() : null;
        dataObject.put(key, valueStr);
      }
    }
    notificationJson.put("data", dataObject);
    JSObject actionJson = new JSObject();
    actionJson.put("actionId", "tap");
    actionJson.put("notification", notificationJson);
    notifyListeners("pushNotificationActionPerformed", actionJson, true);
  }
}
 
Example #6
Source File: AdMob.java    From capacitor-admob with MIT License 6 votes vote down vote up
@PluginMethod()
public void resumeBanner(PluginCall call) {
    try {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mAdViewLayout != null && mAdView != null) {
                    mAdViewLayout.setVisibility(View.VISIBLE);
                    mAdView.resume();
                    Log.d(getLogTag(), "Banner AD Resumed");
                }
            }
        });

        call.success(new JSObject().put("value", true));

    }catch (Exception ex) {
        call.error(ex.getLocalizedMessage(), ex);
    }
}
 
Example #7
Source File: Geolocation.java    From OsmGo with MIT License 6 votes vote down vote up
private JSObject getJSObjectForLocation(Location location) {
  JSObject ret = new JSObject();
  JSObject coords = new JSObject();
  ret.put("coords", coords);
  ret.put("timestamp", location.getTime());
  coords.put("latitude", location.getLatitude());
  coords.put("longitude", location.getLongitude());
  coords.put("accuracy", location.getAccuracy());
  coords.put("altitude", location.getAltitude());
  if (Build.VERSION.SDK_INT >= 26) {
    coords.put("altitudeAccuracy", location.getVerticalAccuracyMeters());
  }
  coords.put("speed", location.getSpeed());
  coords.put("heading", location.getBearing());
  return ret;
}
 
Example #8
Source File: Camera.java    From OsmGo with MIT License 6 votes vote down vote up
private void showPrompt(final PluginCall call) {
  // We have all necessary permissions, open the camera
  JSObject fromPhotos = new JSObject();
  fromPhotos.put("title", "From Photos");
  JSObject takePicture = new JSObject();
  takePicture.put("title", "Take Picture");
  Object[] options = new Object[] {
    fromPhotos,
    takePicture
  };

  Dialogs.actions(getActivity(), options, new Dialogs.OnSelectListener() {
    @Override
    public void onSelect(int index) {
      if (index == 0) {
        openPhotos(call);
      } else if (index == 1) {
        openCamera(call);
      }
    }
  });
}
 
Example #9
Source File: App.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void canOpenUrl(PluginCall call) {
  String url = call.getString("url");
  if (url == null) {
    call.error("Must supply a url");
    return;
  }

  Context ctx = this.getActivity().getApplicationContext();
  final PackageManager pm = ctx.getPackageManager();

  JSObject ret = new JSObject();
  try {
    pm.getPackageInfo(url, PackageManager.GET_ACTIVITIES);
    ret.put("value", true);
    call.success(ret);
    return;
  } catch(PackageManager.NameNotFoundException e) {
    Log.e(getLogTag(), "Package name '"+url+"' not found!");
  }

  ret.put("value", false);
  call.success(ret);
}
 
Example #10
Source File: ConfigUtils.java    From capacitor-oauth2 with MIT License 6 votes vote down vote up
public static Map<String, String> getParamMap(JSObject data, String key) {
    Map<String, String> map = new HashMap<>();
    String k = getDeepestKey(key);
    try {
        JSONObject o = getDeepestObject(data, key);
        JSONObject jsonObject = o.getJSONObject(k);
        Iterator<String> keys = jsonObject.keys();
        if (keys != null) {
            while (keys.hasNext()) {
                String mapKey = keys.next();
                if (mapKey != null && mapKey.trim().length() > 0) {
                    String mapValue = jsonObject.getString(mapKey);
                    if (mapValue != null) {
                        map.put(mapKey, mapValue);
                    }
                }
            }
        }
    } catch (Exception ignore) {
    }
    return map;
}
 
Example #11
Source File: CapacitorFirebaseAuth.java    From capacitor-firebase-auth with MIT License 6 votes vote down vote up
@PluginMethod()
public void signIn(PluginCall call) {
    if (!call.getData().has("providerId")) {
        call.reject("The provider id is required");
        return;
    }

    ProviderHandler handler = this.getProviderHandler(call);

    if (handler == null) {
        Log.w(PLUGIN_TAG, "Provider not supported");
        call.reject("The provider is disable or unsupported");
    } else {

        if (handler.isAuthenticated()) {
            JSObject jsResult = this.build(null, call);
            call.success(jsResult);
        } else {
            this.saveCall(call);
            handler.signIn(call);
        }

    }
}
 
Example #12
Source File: App.java    From OsmGo with MIT License 6 votes vote down vote up
/**
 * Handle ACTION_VIEW intents to store a URL that was used to open the app
 * @param intent
 */
@Override
protected void handleOnNewIntent(Intent intent) {
  super.handleOnNewIntent(intent);

  final String intentString = intent.getDataString();

  // read intent
  String action = intent.getAction();
  Uri url = intent.getData();

  if (!Intent.ACTION_VIEW.equals(action) || url == null) {
    return;
  }

  JSObject ret = new JSObject();
  ret.put("url", url.toString());
  notifyListeners(EVENT_URL_OPEN, ret, true);
}
 
Example #13
Source File: PhoneProviderHandler.java    From capacitor-firebase-auth with MIT License 6 votes vote down vote up
@Override
public void signIn(PluginCall call) {
    if (!call.getData().has("data")) {
        call.reject("The auth data is required");
        return;
    }

    JSObject data = call.getObject("data", new JSObject());

    String phone = data.getString("phone", "");
    if (phone.equalsIgnoreCase("null") || phone.equalsIgnoreCase("")) {
        call.reject("The phone number is required");
        return;
    }

    String code = data.getString("verificationCode", "");
    if(code.equalsIgnoreCase("null") || code.equalsIgnoreCase("")) {
        PhoneAuthProvider.getInstance().verifyPhoneNumber
                (phone, 60, TimeUnit.SECONDS, this.plugin.getActivity(), this.mCallbacks);
    } else {
        AuthCredential credential = PhoneAuthProvider.getCredential(this.mVerificationId, code);
        this.mVerificationCode = code;
        plugin.handleAuthCredentials(credential);
    }
}
 
Example #14
Source File: CapacitorFirebaseAuth.java    From capacitor-firebase-auth with MIT License 6 votes vote down vote up
public void handleAuthCredentials(AuthCredential credential) {
    final PluginCall savedCall = getSavedCall();
    if (savedCall == null) {
        Log.d(PLUGIN_TAG, "No saved call on activity result.");
        return;
    }

    if (credential == null) {
        Log.w(PLUGIN_TAG, "Sign In failure: credentials.");
        savedCall.reject("Sign In failure: credentials.");
        return;
    }

    if (this.nativeAuth) {
        nativeAuth(savedCall, credential);
    } else {
        JSObject jsResult = this.build(credential, savedCall);
        savedCall.success(jsResult);
    }
}
 
Example #15
Source File: DownloaderPlugin.java    From capacitor-downloader with MIT License 5 votes vote down vote up
@PluginMethod()
public void getStatus(PluginCall call) {
    String id = call.getString("id");
    DownloadData data = downloadsData.get(id);
    JSObject jsObject = new JSObject();
    if (data != null) {
        jsObject.put("value", data.getStatus());
    }
    call.resolve(jsObject);
}
 
Example #16
Source File: Storage.java    From OsmGo with MIT License 5 votes vote down vote up
@PluginMethod()
public void get(PluginCall call) {
  String key = call.getString("key");
  if (key == null) {
    call.reject("Must provide key");
    return;
  }
  String value = prefs.getString(key, null);

  JSObject ret = new JSObject();
  ret.put("value", value == null ? JSObject.NULL : value);
  call.resolve(ret);
}
 
Example #17
Source File: Permissions.java    From OsmGo with MIT License 5 votes vote down vote up
private void checkPerm(String perm, PluginCall call) {
  JSObject ret = new JSObject();
  if (ContextCompat.checkSelfPermission(getContext(), perm) == PackageManager.PERMISSION_DENIED) {
    ret.put("state", "denied");
  } else if (ContextCompat.checkSelfPermission(getContext(), perm) == PackageManager.PERMISSION_GRANTED) {
    ret.put("state", "granted");
  } else {
    ret.put("state", "prompt");
  }
  call.resolve(ret);
}
 
Example #18
Source File: Camera.java    From OsmGo with MIT License 5 votes vote down vote up
private void returnDataUrl(PluginCall call, ExifWrapper exif, ByteArrayOutputStream bitmapOutputStream) {
  byte[] byteArray = bitmapOutputStream.toByteArray();
  String encoded = Base64.encodeToString(byteArray, Base64.NO_WRAP);

  JSObject data = new JSObject();
  data.put("format", "jpeg");
  data.put("dataUrl", "data:image/jpeg;base64," + encoded);
  data.put("exif", exif.toJson());
  call.resolve(data);
}
 
Example #19
Source File: NotificationAction.java    From OsmGo with MIT License 5 votes vote down vote up
public static Map<String, NotificationAction[]> buildTypes(JSArray types) {
  Map<String, NotificationAction[]> actionTypeMap = new HashMap<>();
  try {
    List<JSONObject> objects = types.toList();
    for (JSONObject obj : objects) {
      JSObject jsObject = JSObject.fromJSONObject(obj);
      String actionGroupId = jsObject.getString("id");
      if (actionGroupId == null) {
        return null;
      }
      JSONArray actions = jsObject.getJSONArray("actions");
      if (actions != null) {
        NotificationAction[] typesArray = new NotificationAction[actions.length()];
        for (int i = 0; i < typesArray.length; i++) {
          NotificationAction notificationAction = new NotificationAction();
          JSObject action = JSObject.fromJSONObject(actions.getJSONObject(i));
          notificationAction.setId(action.getString("id"));
          notificationAction.setTitle(action.getString("title"));
          notificationAction.setInput(action.getBool("input"));
          typesArray[i] = notificationAction;
        }
        actionTypeMap.put(actionGroupId, typesArray);
      }
    }
  } catch (Exception e) {
    Log.e(LogUtils.getPluginTag("LN"), "Error when building action types", e);
  }
  return actionTypeMap;
}
 
Example #20
Source File: LocalNotification.java    From OsmGo with MIT License 5 votes vote down vote up
public static JSObject buildLocalNotificationPendingList(List<String> ids) {
  JSObject result = new JSObject();
  JSArray jsArray = new JSArray();
  for (String id : ids) {
    JSObject notification = new JSObject();
    notification.put("id", id);
    jsArray.put(notification);
  }
  result.put("notifications", jsArray);
  return result;
}
 
Example #21
Source File: Accessibility.java    From OsmGo with MIT License 5 votes vote down vote up
public void load() {
  am = (AccessibilityManager) getContext().getSystemService(ACCESSIBILITY_SERVICE);

  am.addTouchExplorationStateChangeListener(new AccessibilityManager.TouchExplorationStateChangeListener() {
    @Override
    public void onTouchExplorationStateChanged(boolean b) {
      JSObject ret = new JSObject();
      ret.put("value", b);
      notifyListeners(EVENT_SCREEN_READER_STATE_CHANGE, ret);
    }
  });
}
 
Example #22
Source File: Modals.java    From OsmGo with MIT License 5 votes vote down vote up
@PluginMethod()
public void showActions(final PluginCall call) {
  String title = call.getString("title");
  String message = call.getString("message", "");
  JSArray options = call.getArray("options");

  if (title == null) {
    call.error("Must supply a title");
    return;
  }

  if (options == null) {
    call.error("Must supply options");
    return;
  }

  if (getActivity().isFinishing()) {
    call.error("App is finishing");
    return;
  }

  final ModalsBottomSheetDialogFragment fragment = new ModalsBottomSheetDialogFragment();
  fragment.setOptions(options);
  fragment.setOnSelectedListener(new ModalsBottomSheetDialogFragment.OnSelectedListener() {
    @Override
    public void onSelected(int index) {
      JSObject ret = new JSObject();
      ret.put("index", index);
      call.success(ret);
      fragment.dismiss();
    }
  });
  fragment.show(getActivity().getSupportFragmentManager(), "capacitorModalsActionSheet");
}
 
Example #23
Source File: AdmobPlus.java    From admob-plus with MIT License 5 votes vote down vote up
@PluginMethod()
public void echo(PluginCall call) {
    String value = call.getString("value");

    JSObject ret = new JSObject();
    ret.put("value", value);
    call.success(ret);
}
 
Example #24
Source File: OAuth2ClientPluginTest.java    From capacitor-oauth2 with MIT License 5 votes vote down vote up
@Test
public void responseTypeToken() {
    JSObject jsObject = loadJson(R.raw.response_type_token);
    OAuth2Options options = plugin.buildAuthenticateOptions(jsObject);
    Assert.assertNotNull(options);
    Assert.assertEquals("CLIENT_ID_ANDROID", options.getAppId());
    Assert.assertEquals("token", options.getResponseType().toLowerCase());
    Assert.assertTrue(options.isHandleResultOnActivityResult());
}
 
Example #25
Source File: Modals.java    From OsmGo with MIT License 5 votes vote down vote up
@PluginMethod()
public void confirm(final PluginCall call) {
  final Activity c = this.getActivity();
  final String title = call.getString("title");
  final String message = call.getString("message");
  final String okButtonTitle = call.getString("okButtonTitle", "OK");
  final String cancelButtonTitle = call.getString("cancelButtonTitle", "Cancel");

  if(title == null || message == null) {
    call.error("Please provide a title or message for the alert");
    return;
  }

  if (c.isFinishing()) {
    call.error("App is finishing");
    return;
  }

  Dialogs.confirm(c, message, title, okButtonTitle, cancelButtonTitle, new Dialogs.OnResultListener() {
    @Override
    public void onResult(boolean value, boolean didCancel, String inputValue) {
      JSObject ret = new JSObject();
      ret.put("value", value);
      call.success(ret);
    }
  });
}
 
Example #26
Source File: DownloaderPlugin.java    From capacitor-downloader with MIT License 5 votes vote down vote up
@PluginMethod()
public void getPath(PluginCall call) {
    String id = call.getString("id");
    DownloadData data = downloadsData.get(id);
    JSObject jsObject = new JSObject();
    if (data != null) {
        jsObject.put("value", data.getPath());
    }
    call.resolve(jsObject);
}
 
Example #27
Source File: DownloaderPlugin.java    From capacitor-downloader with MIT License 5 votes vote down vote up
@Override
public void onUIComplete(String task) {
    DownloadData data = downloadsData.get(task);
    Request request = downloadsRequest.get(task);
    if (data != null) {
        JSObject object = new JSObject();
        object.put("status", StatusCode.COMPLETED);
        String path = FileUtils.getPortablePath(getContext(), bridge.getLocalUrl(), Uri.fromFile(new File(request.getFilePath(), request.getFileName())));
        object.put("path", path);
        data.getCallback().success(object);
        downloadsData.remove(task);
        downloadsRequest.remove(task);
    }

}
 
Example #28
Source File: DownloaderPlugin.java    From capacitor-downloader with MIT License 5 votes vote down vote up
@Override
public void onUIProgress(String task, long currentBytes, long totalBytes, long speed) {
    DownloadData data = downloadsData.get(task);
    if (data != null) {
        JSObject object = new JSObject();
        object.put("value", (currentBytes * 100 / totalBytes));
        object.put("speed", speed);
        object.put("currentSize", currentBytes);
        object.put("totalSize", totalBytes);
        data.getCallback().success(object);
    }

}
 
Example #29
Source File: OAuth2ClientPluginTest.java    From capacitor-oauth2 with MIT License 5 votes vote down vote up
@Test
public void buildRefreshTokenOptions() {
    JSObject jsObject = loadJson(R.raw.refresh_token_config);
    OAuth2RefreshTokenOptions options = plugin.buildRefreshTokenOptions(jsObject);
    Assert.assertNotNull(options);
    Assert.assertNotNull(options.getAppId());
    Assert.assertNotNull(options.getAccessTokenEndpoint());
    Assert.assertNotNull(options.getRefreshToken());
    Assert.assertNotNull(options.getScope());
}
 
Example #30
Source File: OAuth2ClientPluginTest.java    From capacitor-oauth2 with MIT License 5 votes vote down vote up
@Test
public void serverAuthorizationHandling() {
    JSObject jsObject = loadJson(R.raw.server_authorization_handling);
    OAuth2Options options = plugin.buildAuthenticateOptions(jsObject);
    Assert.assertNotNull(options.getAppId());
    Assert.assertNotNull(options.getAuthorizationBaseUrl());
    Assert.assertNotNull(options.getResponseType());
    Assert.assertNotNull(options.getRedirectUrl());
}