com.getcapacitor.PluginMethod Java Examples

The following examples show how to use com.getcapacitor.PluginMethod. 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: 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 #2
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 #3
Source File: AdMob.java    From capacitor-admob with MIT License 6 votes vote down vote up
@PluginMethod()
public void initialize(PluginCall call) {
    /* Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 */
    String appId = call.getString("appId", "ca-app-pub-3940256099942544~3347511713");

    try {
        MobileAds.initialize(this.getContext(), appId);

        mViewGroup = (ViewGroup) ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);

        call.success();

    }catch (Exception ex) {
        call.error(ex.getLocalizedMessage(), ex);
    }
}
 
Example #4
Source File: AdMob.java    From capacitor-admob with MIT License 6 votes vote down vote up
@PluginMethod()
public void showRewardVideoAd(final PluginCall call) {
    try {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mRewardedVideoAd != null && mRewardedVideoAd.isLoaded()) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mRewardedVideoAd.show();
                        }
                    });
                    call.success(new JSObject().put("value", true));
                }else {
                    call.error("The RewardedVideoAd wasn't loaded yet.");
                }
            }
        });

    }catch (Exception ex) {
        call.error(ex.getLocalizedMessage(), ex);
    }
}
 
Example #5
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 #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: AdMob.java    From capacitor-admob with MIT License 6 votes vote down vote up
@PluginMethod()
public void removeBanner(PluginCall call) {
    try {
        if (mAdView != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mAdView != null) {
                        mViewGroup.removeView(mAdViewLayout);
                        mAdViewLayout.removeView(mAdView);
                        mAdView.destroy();
                        mAdView = null;
                        Log.d(getLogTag(), "Banner AD Removed");
                    }
                }
            });
        }

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

    }catch (Exception ex) {
        call.error(ex.getLocalizedMessage(), ex);
    }
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: Keyboard.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void hide(final PluginCall call) {
  execute(new Runnable() {
    @Override
    public void run() {
      //http://stackoverflow.com/a/7696791/1091751
      InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
      View v = getActivity().getCurrentFocus();

      if (v == null) {
        call.error("Can't close keyboard, not currently focused");
      } else {
        inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        call.success(); // Thread-safe.
      }
    }
  });
}
 
Example #15
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 #16
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 #17
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 #18
Source File: Modals.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void alert(final PluginCall call) {
  final Activity c = this.getActivity();
  final String title = call.getString("title");
  final String message = call.getString("message");
  final String buttonTitle = call.getString("buttonTitle", "OK");

  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.alert(c, message, title, buttonTitle, new Dialogs.OnResultListener() {
    @Override
    public void onResult(boolean value, boolean didCancel, String inputValue) {
      call.success();
    }
  });
}
 
Example #19
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 #20
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 #21
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 #22
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 #23
Source File: Haptics.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
@SuppressWarnings("MissingPermission")
public void vibrate(PluginCall call) {
  Context c = this.getContext();
  int duration = call.getInt("duration", 300);

  if(!hasPermission(Manifest.permission.VIBRATE)) {
    call.error("Can't vibrate: Missing VIBRATE permission in AndroidManifest.xml");
    return;
  }

  if (Build.VERSION.SDK_INT >= 26) {
    ((Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE));
  } else {
    vibratePre26(duration);
  }

  call.success();
}
 
Example #24
Source File: Accessibility.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void speak(PluginCall call) {
  final String value = call.getString("value");
  final String language = call.getString("language", "en");
  final Locale locale = Locale.forLanguageTag(language);

  if (locale == null) {
    call.error("Language was not a valid language tag.");
    return;
  }

  tts = new TextToSpeech(getContext(), new TextToSpeech.OnInitListener() {
    @Override
    public void onInit(int i) {
      tts.setLanguage(locale);
      tts.speak(value, TextToSpeech.QUEUE_FLUSH, null, "capacitoraccessibility" + System.currentTimeMillis());
    }
  });

  // Not yet implemented
  throw new UnsupportedOperationException();
}
 
Example #25
Source File: Clipboard.java    From OsmGo with MIT License 6 votes vote down vote up
@PluginMethod()
public void write(PluginCall call) {
  String strVal = call.getString("string");
  String imageVal = call.getString("image");
  String urlVal = call.getString("url");
  String label = call.getString("label");

  Context c = getContext();
  ClipboardManager clipboard = (ClipboardManager)
      c.getSystemService(Context.CLIPBOARD_SERVICE);

  ClipData data = null;
  if(strVal != null) {
    data = ClipData.newPlainText(label, strVal);
  } else if(imageVal != null) {
    // Does nothing
  } else if(urlVal != null) {
    data = ClipData.newPlainText(label, urlVal);
  }

  if(data != null) {
    clipboard.setPrimaryClip(data);
  }

  call.success();
}
 
Example #26
Source File: StatusBar.java    From OsmGo with MIT License 5 votes vote down vote up
@PluginMethod()
public void hide(final PluginCall call) {
  // Hide the status bar.
  getBridge().executeOnMainThread(new Runnable() {
    @Override
    public void run() {
      View decorView = getActivity().getWindow().getDecorView();
      int uiOptions = decorView.getSystemUiVisibility();
      uiOptions = uiOptions | View.SYSTEM_UI_FLAG_FULLSCREEN;
      uiOptions = uiOptions & ~View.SYSTEM_UI_FLAG_VISIBLE;
      decorView.setSystemUiVisibility(uiOptions);
      call.success();
    }
  });
}
 
Example #27
Source File: Geolocation.java    From OsmGo with MIT License 5 votes vote down vote up
@PluginMethod()
public void getCurrentPosition(PluginCall call) {
  if (!hasRequiredPermissions()) {
    saveCall(call);
    pluginRequestAllPermissions();
  } else {
    sendLocation(call);
  }
}
 
Example #28
Source File: Geolocation.java    From OsmGo with MIT License 5 votes vote down vote up
@PluginMethod(returnType=PluginMethod.RETURN_CALLBACK)
public void watchPosition(PluginCall call) {
  call.save();
  if (!hasRequiredPermissions()) {
    saveCall(call);
    pluginRequestAllPermissions();
  } else {
    startWatch(call);
  }
}
 
Example #29
Source File: LocalNotifications.java    From OsmGo with MIT License 5 votes vote down vote up
@PluginMethod()
public void registerActionTypes(PluginCall call) {
  JSArray types = call.getArray("types");
  Map<String, NotificationAction[]> typesArray = NotificationAction.buildTypes(types);
  notificationStorage.writeActionGroup(typesArray);
  call.success();
}
 
Example #30
Source File: Filesystem.java    From OsmGo with MIT License 5 votes vote down vote up
@PluginMethod()
public void mkdir(PluginCall call) {
  saveCall(call);
  String path = call.getString("path");
  String directory = getDirectoryParameter(call);
  boolean intermediate = call.getBoolean("createIntermediateDirectories", false).booleanValue();

  File fileObject = getFileObject(path, directory);

  if (fileObject.exists()) {
    call.error("Directory exists");
    return;
  }

  if (!isPublicDirectory(directory)
          || isStoragePermissionGranted(PluginRequestCodes.FILESYSTEM_REQUEST_WRITE_FOLDER_PERMISSIONS, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
    boolean created = false;
    if (intermediate) {
      created = fileObject.mkdirs();
    } else {
      created = fileObject.mkdir();
    }
    if(created == false) {
      call.error("Unable to create directory, unknown reason");
    } else {
      call.success();
    }
  }
}