com.getcapacitor.PluginCall Java Examples

The following examples show how to use com.getcapacitor.PluginCall. 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: Camera.java    From OsmGo with MIT License 7 votes vote down vote up
private void editImage(PluginCall call, Uri uri) {
  try {
    Uri origPhotoUri = uri;
    if (imageFileUri != null) {
      origPhotoUri = imageFileUri;
    }
    Intent editIntent = new Intent(Intent.ACTION_EDIT);
    editIntent.setDataAndType(origPhotoUri, "image/*");
    File editedFile = CameraUtils.createImageFile(getActivity(), false);
    Uri editedUri = Uri.fromFile(editedFile);
    editIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    editIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    editIntent.putExtra(MediaStore.EXTRA_OUTPUT, editedUri);
    startActivityForResult(call, editIntent, REQUEST_IMAGE_EDIT);
  } catch (Exception ex) {
    call.error(IMAGE_EDIT_ERROR, ex);
  }
}
 
Example #2
Source File: Camera.java    From OsmGo with MIT License 6 votes vote down vote up
private boolean checkCameraPermissions(PluginCall call) {
  // If we want to save to the gallery, we need two permissions
  if(settings.isSaveToGallery() && !(hasPermission(Manifest.permission.CAMERA) && hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
    pluginRequestPermissions(new String[] {
      Manifest.permission.CAMERA,
      Manifest.permission.WRITE_EXTERNAL_STORAGE,
      Manifest.permission.READ_EXTERNAL_STORAGE
    }, REQUEST_IMAGE_CAPTURE);
    return false;
  }
  // If we don't need to save to the gallery, we can just ask for camera permissions
  else if(!hasPermission(Manifest.permission.CAMERA)) {
    pluginRequestPermission(Manifest.permission.CAMERA, REQUEST_IMAGE_CAPTURE);
    return false;
  }
  return true;
}
 
Example #3
Source File: Camera.java    From OsmGo with MIT License 6 votes vote down vote up
private void doShow(PluginCall call) {
  switch (settings.getSource()) {
    case PROMPT:
      showPrompt(call);
      break;
    case CAMERA:
      showCamera(call);
      break;
    case PHOTOS:
      showPhotos(call);
      break;
    default:
      showPrompt(call);
      break;
  }
}
 
Example #4
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 #5
Source File: CapacitorFirebaseAuth.java    From capacitor-firebase-auth with MIT License 6 votes vote down vote up
@Override
protected void handleOnActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(PLUGIN_TAG, "Handle on Activity Result");

    final PluginCall savedCall = getSavedCall();
    if (savedCall == null) {
        Log.d(PLUGIN_TAG, "No saved call on activity result.");
        return;
    }

    final ProviderHandler handler = this.providerHandlerByRC.get(requestCode);
    if (handler == null) {
        Log.w(PLUGIN_TAG, "No provider handler with given request code.");
        savedCall.reject("No provider handler with given request code.");
    } else {
        handler.handleOnActivityResult(requestCode, resultCode, data);
    }
}
 
Example #6
Source File: Filesystem.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void stat(PluginCall call) {
  saveCall(call);
  String path = call.getString("path");
  String directory = getDirectoryParameter(call);

  File fileObject = getFileObject(path, directory);

  if (!isPublicDirectory(directory)
      || isStoragePermissionGranted(PluginRequestCodes.FILESYSTEM_REQUEST_STAT_PERMISSIONS, Manifest.permission.READ_EXTERNAL_STORAGE)) {
    if (!fileObject.exists()) {
      call.error("File does not exist");
      return;
    }

    JSObject data = new JSObject();
    data.put("type", fileObject.isDirectory() ? "directory" : "file");
    data.put("size", fileObject.length());
    data.put("ctime", null);
    data.put("mtime", fileObject.lastModified());
    data.put("uri", Uri.fromFile(fileObject).toString());
    call.success(data);
  }
}
 
Example #7
Source File: Geolocation.java    From OsmGo with MIT License 6 votes vote down vote up
@SuppressWarnings("MissingPermission")
@PluginMethod()
public void clearWatch(PluginCall call) {
  String callbackId = call.getString("id");
  if (callbackId != null) {
    PluginCall removed = watchingCalls.remove(callbackId);
    if (removed != null) {
      removed.release(bridge);
    }
  }

  if (watchingCalls.size() == 0) {
    locationManager.removeUpdates(locationListener);
  }

  call.success();
}
 
Example #8
Source File: Filesystem.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void readdir(PluginCall call) {
  saveCall(call);
  String path = call.getString("path");
  String directory = getDirectoryParameter(call);

  File fileObject = getFileObject(path, directory);

   if (!isPublicDirectory(directory)
       || isStoragePermissionGranted(PluginRequestCodes.FILESYSTEM_REQUEST_READ_FOLDER_PERMISSIONS, Manifest.permission.READ_EXTERNAL_STORAGE)) {
    if (fileObject != null && fileObject.exists()) {
      String[] files = fileObject.list();

      JSObject ret = new JSObject();
      ret.put("files", JSArray.from(files));
      call.success(ret);
    } else {
    call.error("Directory does not exist");
    }
  }
}
 
Example #9
Source File: Geolocation.java    From OsmGo with MIT License 6 votes vote down vote up
/**
 * Given the call's options, return a Criteria object
 * that will indicate which location provider we need to use.
 * @param call
 * @return
 */
private Criteria getCriteriaForCall(PluginCall call) {
  boolean enableHighAccuracy = call.getBoolean("enableHighAccuracy", false);
  boolean altitudeRequired = call.getBoolean("altitudeRequired", false);
  boolean speedRequired = call.getBoolean("speedRequired", false);
  boolean bearingRequired = call.getBoolean("bearingRequired", false);

  int timeout = call.getInt("timeout", 30000);
  int maximumAge = call.getInt("maximumAge", 0);

  Criteria c = new Criteria();
  c.setAccuracy(enableHighAccuracy ? Criteria.ACCURACY_FINE : Criteria.ACCURACY_COARSE);
  c.setAltitudeRequired(altitudeRequired);
  c.setBearingRequired(bearingRequired);
  c.setSpeedRequired(speedRequired);
  return c;
}
 
Example #10
Source File: StatusBar.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void setBackgroundColor(final PluginCall call) {
  final String color = call.getString("color");
  if (color == null) {
    call.error("Color must be provided");
    return;
  }

  getBridge().executeOnMainThread(new Runnable() {
    @Override
    public void run() {
      Window window = getActivity().getWindow();
      window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
      window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
      try {
        window.setStatusBarColor(Color.parseColor(color.toUpperCase()));
        call.success();
      } catch (IllegalArgumentException ex) {
        call.error("Invalid color provided. Must be a hex string (ex: #ff0000");
      }
    }
  });
}
 
Example #11
Source File: Camera.java    From OsmGo with MIT License 6 votes vote down vote up
private CameraSettings getSettings(PluginCall call) {
  CameraSettings settings = new CameraSettings();
  settings.setResultType(getResultType(call.getString("resultType")));
  settings.setSaveToGallery(call.getBoolean("saveToGallery", CameraSettings.DEFAULT_SAVE_IMAGE_TO_GALLERY));
  settings.setAllowEditing(call.getBoolean("allowEditing", false));
  settings.setQuality(call.getInt("quality", CameraSettings.DEFAULT_QUALITY));
  settings.setWidth(call.getInt("width", 0));
  settings.setHeight(call.getInt("height", 0));
  settings.setShouldResize(settings.getWidth() > 0 || settings.getHeight() > 0);
  settings.setShouldCorrectOrientation(call.getBoolean("correctOrientation", CameraSettings.DEFAULT_CORRECT_ORIENTATION));
  try {
    settings.setSource(CameraSource.valueOf(call.getString("source", CameraSource.PROMPT.getSource())));
  } catch (IllegalArgumentException ex) {
    settings.setSource(CameraSource.PROMPT);
  }
  return settings;
}
 
Example #12
Source File: Filesystem.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void deleteFile(PluginCall call) {
  saveCall(call);
  String file = call.getString("path");
  String directory = getDirectoryParameter(call);

  File fileObject = getFileObject(file, directory);

  if (!isPublicDirectory(directory)
      || isStoragePermissionGranted(PluginRequestCodes.FILESYSTEM_REQUEST_DELETE_FILE_PERMISSIONS, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
    if (!fileObject.exists()) {
      call.error("File does not exist");
      return;
    }

    boolean deleted = fileObject.delete();
    if(deleted == false) {
      call.error("Unable to delete file");
    } else {
      call.success();
    }
  }
}
 
Example #13
Source File: BackgroundTask.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod(returnType=PluginMethod.RETURN_CALLBACK)
public void beforeExit(PluginCall call) {
  String taskId = "";

  /*
  serviceIntent = new Intent(getActivity(), BackgroundTaskService.class);
  serviceIntent.putExtra("taskId", call.getCallbackId());
  getActivity().startService(serviceIntent);
  */

  // No-op for now as Android has less strict requirements for background tasks

  JSObject ret = new JSObject();
  ret.put("taskId", call.getCallbackId());
  call.success(ret);
}
 
Example #14
Source File: FCMPlugin.java    From capacitor-fcm with MIT License 6 votes vote down vote up
@PluginMethod()
public void deleteInstance(final PluginCall call) {
    Runnable r = () -> {
        try {
            FirebaseInstanceId.getInstance().deleteInstanceId();
            call.success();
        } catch (IOException e) {
            e.printStackTrace();
            call.error("Cant delete Firebase Instance ID", e);
        }
    };

    // Run in background thread since `deleteInstanceId()` is a blocking request.
    // See https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId#deleteInstanceId()
    new Thread(r).start();
}
 
Example #15
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 #16
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 #17
Source File: AdMob.java    From capacitor-admob with MIT License 6 votes vote down vote up
@PluginMethod()
public void hideBanner(PluginCall call) {
    try {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mAdViewLayout != null) {
                    mAdViewLayout.setVisibility(View.GONE);
                    mAdView.pause();
                }
            }
        });

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

    }catch (Exception ex) {
        call.error(ex.getLocalizedMessage(), ex);
    }
}
 
Example #18
Source File: Browser.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void prefetch(PluginCall call) {
  JSArray urls = call.getArray("urls");
  if (urls == null || urls.length() == 0) {
    call.error("Must provide an array of URLs to prefetch");
    return;
  }

  CustomTabsSession session = getCustomTabsSession();

  if (session == null) {
    call.error("Browser session isn't ready yet");
    return;
  }

  try {
    for (String url : urls.<String>toList()) {
      session.mayLaunchUrl(Uri.parse(url), null, null);
    }
  } catch(JSONException ex) {
    call.error("Unable to process provided urls list. Ensure each item is a string and valid URL", ex);
    return;
  }
}
 
Example #19
Source File: Toast.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void show(PluginCall call) {
  CharSequence text = call.getString("text");
  if(text == null) {
    call.error("Must provide text");
    return;
  }

  String durationType = call.getString("durationType", "short");

  int duration = android.widget.Toast.LENGTH_SHORT;
  if("long".equals(durationType)) {
    duration = android.widget.Toast.LENGTH_LONG;
  }

  android.widget.Toast toast = android.widget.Toast.makeText(getContext(), text, duration);
  toast.show();
  call.success();
}
 
Example #20
Source File: AdMob.java    From capacitor-admob with MIT License 6 votes vote down vote up
@PluginMethod()
public void showInterstitial(final PluginCall call) {
    try {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
            if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mInterstitialAd.show();
                    }
                });
                call.success(new JSObject().put("value", true));
            } else {
                call.error("The interstitial wasn't loaded yet.");
            }
            }
        });
    }catch (Exception ex){
        call.error(ex.getLocalizedMessage(), ex);
    }
}
 
Example #21
Source File: PushNotifications.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void listChannels(PluginCall call) {
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    List<NotificationChannel> notificationChannels = notificationManager.getNotificationChannels();
    JSArray channels = new JSArray();
    for (NotificationChannel notificationChannel : notificationChannels) {
      JSObject channel = new JSObject();
      channel.put(CHANNEL_ID, notificationChannel.getId());
      channel.put(CHANNEL_NAME, notificationChannel.getName());
      channel.put(CHANNEL_DESCRIPTION, notificationChannel.getDescription());
      channel.put(CHANNEL_IMPORTANCE, notificationChannel.getImportance());
      channel.put(CHANNEL_VISIBILITY, notificationChannel.getLockscreenVisibility());
      Log.d(getLogTag(), "visibility " + notificationChannel.getLockscreenVisibility());
      Log.d(getLogTag(), "importance " + notificationChannel.getImportance());
      channels.put(channel);
    }
    JSObject result = new JSObject();
    result.put("channels", channels);
    call.success(result);
  } else {
    call.unavailable();
  }
}
 
Example #22
Source File: LocalNotificationManager.java    From OsmGo with MIT License 6 votes vote down vote up
@Nullable
public JSONArray schedule(PluginCall call, List<LocalNotification> localNotifications) {
  JSONArray ids = new JSONArray();
  NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

  boolean notificationsEnabled = notificationManager.areNotificationsEnabled();
  if (!notificationsEnabled) {
    call.error("Notifications not enabled on this device");
    return null;
  }
  for (LocalNotification localNotification : localNotifications) {
    Integer id = localNotification.getId();
    if (localNotification.getId() == null) {
      call.error("LocalNotification missing identifier");
      return null;
    }
    dismissVisibleNotification(id);
    cancelTimerForNotification(id);
    buildNotification(notificationManager, localNotification, call);
    ids.put(id);
  }
  return ids;
}
 
Example #23
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 #24
Source File: Permissions.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod
public void query(PluginCall call) {
  String name = call.getString("name");

  switch (name) {
    case "camera":
      checkCamera(call);
      break;
    case "photos":
      checkPhotos(call);
      break;
    case "geolocation":
      checkGeo(call);
      break;
    case "notifications":
      checkNotifications(call);
      break;
    case "clipboard-read":
    case "clipboard-write":
      checkClipboard(call);
      break;
    default:
      call.reject("Unknown permission type");
  }
}
 
Example #25
Source File: SplashScreen.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void show(final PluginCall call) {
  int showDuration = call.getInt("showDuration", Splash.DEFAULT_SHOW_DURATION);
  int fadeInDuration = call.getInt("fadeInDuration", Splash.DEFAULT_FADE_IN_DURATION);
  int fadeOutDuration = call.getInt("fadeOutDuration", Splash.DEFAULT_FADE_OUT_DURATION);
  boolean autoHide = call.getBoolean("autoHide", Splash.DEFAULT_AUTO_HIDE);

  Splash.show(getActivity(), showDuration, fadeInDuration, fadeOutDuration, autoHide, new Splash.SplashListener() {
    @Override
    public void completed() {
      call.success();
    }

    @Override
    public void error() {
      call.error("An error occurred while showing splash");
    }
  });
}
 
Example #26
Source File: Geolocation.java    From OsmGo with MIT License 5 votes vote down vote up
private void sendLocation(PluginCall call) {
  String provider = getBestProviderForCall(call);
  Location lastLocation = getBestLocation(provider);
  if (lastLocation == null) {
    call.error("location unavailable");
  } else {
    call.success(getJSObjectForLocation(lastLocation));
  }
}
 
Example #27
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 #28
Source File: Keyboard.java    From OsmGo with MIT License 5 votes vote down vote up
@PluginMethod()
public void show(final PluginCall call) {
  execute(new Runnable() {
    @Override
    public void run() {
      new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
          ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
          call.success(); // Thread-safe.
        }
      }, 350);
    }
  });
}
 
Example #29
Source File: Filesystem.java    From OsmGo with MIT License 5 votes vote down vote up
@PluginMethod()
public void getUri(PluginCall call) {
  saveCall(call);
  String path = call.getString("path");
  String directory = getDirectoryParameter(call);

  File fileObject = getFileObject(path, directory);

  if (!isPublicDirectory(directory)
      || isStoragePermissionGranted(PluginRequestCodes.FILESYSTEM_REQUEST_URI_PERMISSIONS, Manifest.permission.READ_EXTERNAL_STORAGE)) {
    JSObject data = new JSObject();
    data.put("uri", Uri.fromFile(fileObject).toString());
    call.success(data);
  }
}
 
Example #30
Source File: AdmobPlus.java    From admob-plus with MIT License 5 votes vote down vote up
@PluginMethod()
public void interstitial_load(final PluginCall call) {
    final Interstitial interstitial = Ad.createInterstitial(call.getInt("id"), this);
    final AdRequest.Builder builder = createAdRequestBuilder(call);
    bridge.executeOnMainThread(new Runnable() {
        @Override
        public void run() {
            interstitial.load(call.getString("adUnitId"), builder.build());
            call.resolve();
        }
    });
}