org.apache.cordova.CallbackContext Java Examples

The following examples show how to use org.apache.cordova.CallbackContext. 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: CameraPreview.java    From cordova-plugin-camera-preview with MIT License 6 votes vote down vote up
private boolean setZoom(int zoom, CallbackContext callbackContext) {
  if(this.hasCamera(callbackContext) == false){
    return true;
  }

  Camera camera = fragment.getCamera();
  Camera.Parameters params = camera.getParameters();

  if (camera.getParameters().isZoomSupported()) {
    params.setZoom(zoom);
    fragment.setCameraParameters(params);

    callbackContext.success(zoom);
  } else {
    callbackContext.error("Zoom not supported");
  }

  return true;
}
 
Example #2
Source File: BackgroundDownload.java    From cordova-plugin-background-download with Apache License 2.0 6 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {
        if (action.equals("startAsync")) {
            startAsync(args, callbackContext);
            return true;
        }
        if (action.equals("stop")) {
            stop(args, callbackContext);
            return true;
        }
        return false; // invalid action
    } catch (Exception ex) {
        callbackContext.error(ex.getMessage());
    }
    return true;
}
 
Example #3
Source File: CordovaResourceApiTest.java    From cordova-amazon-fireos with Apache License 2.0 6 votes vote down vote up
protected void setUp() throws Exception {
    super.setUp();
    activity = this.getActivity();
    cordovaWebView = activity.cordovaWebView;
    resourceApi = cordovaWebView.getResourceApi();
    resourceApi.setThreadCheckingEnabled(false);
    cordovaWebView.pluginManager.addService(new PluginEntry("CordovaResourceApiTestPlugin1", new CordovaPlugin() {
        @Override
        public Uri remapUri(Uri uri) {
            if (uri.getQuery() != null && uri.getQuery().contains("pluginRewrite")) {
                return cordovaWebView.getResourceApi().remapUri(
                        Uri.parse("data:text/plain;charset=utf-8,pass"));
            }
            return null;
        }
        public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
            synchronized (CordovaResourceApiTest.this) {
                execPayload = args.getString(0);
                execStatus = args.getInt(1);
                CordovaResourceApiTest.this.notify();
            }
            return true;
        }
    }));
}
 
Example #4
Source File: FileTransfer.java    From L.TileLayer.Cordova with MIT License 6 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if (action.equals("upload") || action.equals("download")) {
        String source = args.getString(0);
        String target = args.getString(1);

        if (action.equals("upload")) {
            try {
                source = URLDecoder.decode(source, "UTF-8");
                upload(source, target, args, callbackContext);
            } catch (UnsupportedEncodingException e) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION, "UTF-8 error."));
            }
        } else {
            download(source, target, args, callbackContext);
        }
        return true;
    } else if (action.equals("abort")) {
        String objectId = args.getString(0);
        abort(objectId);
        callbackContext.success();
        return true;
    }
    return false;
}
 
Example #5
Source File: CameraPreview.java    From cordova-plugin-camera-preview with MIT License 6 votes vote down vote up
private boolean setColorEffect(String effect, CallbackContext callbackContext) {
  if(this.hasCamera(callbackContext) == false){
    return true;
  }

  Camera camera = fragment.getCamera();
  Camera.Parameters params = camera.getParameters();

  List<String> supportedColors;
  supportedColors = params.getSupportedColorEffects();

  if(supportedColors.contains(effect)){
    params.setColorEffect(effect);
    fragment.setCameraParameters(params);
    callbackContext.success(effect);
  }else{
    callbackContext.error("Color effect not supported" + effect);
    return true;
  }
  return true;
}
 
Example #6
Source File: SplashScreen.java    From app-icon with MIT License 6 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("hide")) {
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                webView.postMessage("splashscreen", "hide");
            }
        });
    } else if (action.equals("show")) {
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                webView.postMessage("splashscreen", "show");
            }
        });
    } else {
        return false;
    }

    callbackContext.success();
    return true;
}
 
Example #7
Source File: NetworkManager.java    From jpHolo with MIT License 6 votes vote down vote up
/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return                  True if the action was valid, false otherwise.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("getConnectionInfo")) {
        this.connectionCallbackContext = callbackContext;
        NetworkInfo info = sockMan.getActiveNetworkInfo();
        String connectionType = "";
        try {
            connectionType = this.getConnectionInfo(info).get("type").toString();
        } catch (JSONException e) { }

        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    }
    return false;
}
 
Example #8
Source File: BluetoothPrinter.java    From Cordova-Plugin-BTPrinter with Apache License 2.0 6 votes vote down vote up
boolean printTextSizeAlign(CallbackContext callbackContext, String msg, Integer size, Integer align)
        throws IOException {
    try {
        // set unicode
        byte[] new_size = selFontSize(size);
        byte[] new_align = selAlignTitle(align);
        mmOutputStream.write(new_size);
        mmOutputStream.write(new_align);
        mmOutputStream.write(msg.getBytes("iso-8859-1"));
        resetDefaultFontAlign();
        Log.d(LOG_TAG, "PRINT TEXT SENT " + msg);
        callbackContext.success("PRINT TEXT SENT");
        return true;
    } catch (Exception e) {
        String errMsg = e.getMessage();
        Log.e(LOG_TAG, errMsg);
        e.printStackTrace();
        callbackContext.error(errMsg);
    }
    return false;
}
 
Example #9
Source File: CameraPreview.java    From cordova-plugin-camera-preview with MIT License 6 votes vote down vote up
private boolean setFocusMode(String focusMode, CallbackContext callbackContext) {
  if(this.hasCamera(callbackContext) == false){
    return true;
  }

  Camera camera = fragment.getCamera();
  Camera.Parameters params = camera.getParameters();

  List<String> supportedFocusModes;
  List<String> supportedAutoFocusModes = Arrays.asList("auto", "continuous-picture", "continuous-video","macro");
  supportedFocusModes = params.getSupportedFocusModes();
  if (supportedFocusModes.indexOf(focusMode) > -1) {
    params.setFocusMode(focusMode);
    fragment.setCameraParameters(params);
    callbackContext.success(focusMode);
    return true;
  } else {
    callbackContext.error("Focus mode not recognised: " + focusMode);
    return true;
  }
}
 
Example #10
Source File: InterstitialExecutor.java    From cordova-plugin-admob-free with MIT License 6 votes vote down vote up
public PluginResult requestAd(JSONObject options, CallbackContext callbackContext) {
    CordovaInterface cordova = plugin.cordova;

    plugin.config.setInterstitialOptions(options);

    if (interstitialAd == null) {
        callbackContext.error("interstitialAd is null, call createInterstitialView first");
        return null;
    }

    final CallbackContext delayCallback = callbackContext;
    cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (interstitialAd == null) {
                return;
            }
            interstitialAd.loadAd(plugin.buildAdRequest());

            delayCallback.success();
        }
    });

    return null;
}
 
Example #11
Source File: PhoneNumberPlugin.java    From phonenumber with Apache License 2.0 6 votes vote down vote up
@Override
 public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

     if (!GET_METHOD.equals(action)) {
         callbackContext.error("No such method: " + action);
         return (false);
     }

     try {
         TelephonyManager tMgr = (TelephonyManager)this.cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
         String number = tMgr.getLine1Number();
         if ((null == number) || (number.trim().length() <= 0))
	callbackContext.error("Phone number is not available on this device");

Log.i(TAG, "Number is " + number);
         callbackContext.success(number);
     } catch (Throwable t) {
         Log.e(TAG, "Getting phone number", t);
     }

     return (true);
 }
 
Example #12
Source File: FileTransfer.java    From reader with MIT License 6 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if (action.equals("upload") || action.equals("download")) {
        String source = args.getString(0);
        String target = args.getString(1);

        if (action.equals("upload")) {
            upload(source, target, args, callbackContext);
        } else {
            download(source, target, args, callbackContext);
        }
        return true;
    } else if (action.equals("abort")) {
        String objectId = args.getString(0);
        abort(objectId);
        callbackContext.success();
        return true;
    }
    return false;
}
 
Example #13
Source File: Device.java    From reacteu-app with MIT License 6 votes vote down vote up
/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return                  True if the action was valid, false if not.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if ("getDeviceInfo".equals(action)) {
        JSONObject r = new JSONObject();
        r.put("uuid", Device.uuid);
        r.put("version", this.getOSVersion());
        r.put("platform", this.getPlatform());
        r.put("model", this.getModel());
        r.put("manufacturer", this.getManufacturer());
     r.put("isVirtual", this.isVirtual());
        r.put("serial", this.getSerialNumber());
        callbackContext.success(r);
    }
    else {
        return false;
    }
    return true;
}
 
Example #14
Source File: AndroidWearPlugin.java    From cordova-androidwear with Apache License 2.0 6 votes vote down vote up
private void sendData(final CordovaArgs args,
					  final CallbackContext callbackContext) throws JSONException {
	Log.d(TAG, "sendData");

	String connectionId = args.getString(0);
	String data = args.getString(1);
	try {
		if (api != null) {
			api.sendData(connectionId, data);
			callbackContext.success();
		} else {
			callbackContext.error("Service not present");
		}
	} catch (RemoteException e) {
		callbackContext.error(e.getMessage());
	}
}
 
Example #15
Source File: FoxitPdf.java    From cordova-plugin-foxitpdf with Apache License 2.0 6 votes vote down vote up
static void onDocSave(String data) {
    CallbackContext callbackContext = mCallbackArrays.get(CALLBACK_FOR_OPENDOC);
    if (callbackContext != null) {
        try {
            JSONObject obj = new JSONObject();
            obj.put("type", RDK_DOCSAVED_EVENT);
            obj.put("info", data);

            PluginResult result = new PluginResult(PluginResult.Status.OK, obj);
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
        } catch (JSONException ex) {
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
        }
    }
}
 
Example #16
Source File: DeviceInformation.java    From DeviceInformationPlugin with MIT License 6 votes vote down vote up
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    try {
        if (action.equals("get")) {
            TelephonyManager tm = (TelephonyManager) this.cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
            AccountManager am = AccountManager.get(this.cordova.getActivity());

            String result = getDetails(tm,am);
            if (result != null) {
                callbackContext.success(result);
                return true;
            }
        }
        callbackContext.error("Invalid action");
        return false;
    } catch (Exception e) {
        String s = "Exception: " + e.getMessage();

        System.err.println(s);
        callbackContext.error(s);

        return false;
    }
}
 
Example #17
Source File: TwilioVoicePlugin.java    From cordova-plugin-twiliovoicesdk with MIT License 6 votes vote down vote up
/**
 * Changes sound from earpiece to speaker and back
 *
 * @param mode Speaker Mode
 */
public void setSpeaker(final JSONArray arguments, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            String mode = arguments.optString(0);
            if (mode.equals("on")) {
                Log.d(TAG, "SPEAKER");
                audioManager.setMode(AudioManager.MODE_NORMAL);
                audioManager.setSpeakerphoneOn(true);
            } else {
                Log.d(TAG, "EARPIECE");
                audioManager.setMode(AudioManager.MODE_IN_CALL);
                audioManager.setSpeakerphoneOn(false);
            }
        }
    });
}
 
Example #18
Source File: RewardedVideoAd.java    From admob-plus with MIT License 6 votes vote down vote up
public static boolean executeShowAction(Action action, CallbackContext callbackContext) {
    plugin.cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            RewardedVideoAd rewardedVideoAd = (RewardedVideoAd) action.getAd();
            if (rewardedVideoAd != null) {
                rewardedVideoAd.show();
            }

            PluginResult result = new PluginResult(PluginResult.Status.OK, "");
            callbackContext.sendPluginResult(result);
        }
    });

    return true;
}
 
Example #19
Source File: BannerAd.java    From admob-plus with MIT License 6 votes vote down vote up
public static boolean executeShowAction(Action action, CallbackContext callbackContext) {
    plugin.cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            BannerAd bannerAd = (BannerAd) action.getAd();
            if (bannerAd == null) {
                bannerAd = new BannerAd(
                    action.optId(),
                    action.getAdUnitID(),
                    action.getAdSize(),
                    "top".equals(action.optPosition()) ? Gravity.TOP : Gravity.BOTTOM
                );
            }
            bannerAd.show(action.buildAdRequest());
            PluginResult result = new PluginResult(PluginResult.Status.OK, "");
            callbackContext.sendPluginResult(result);
        }
    });

    return true;
}
 
Example #20
Source File: Share.java    From jpHolo with MIT License 6 votes vote down vote up
@Override
public boolean execute(final String action, final JSONArray args,
		final CallbackContext callbackContext) {
	cordova.getThreadPool().execute(new Runnable() {
		@Override
		public void run() {
			try {
				final JSONObject jo = args.getJSONObject(0);
				doSendIntent(jo.getString("subject"), jo.getString("text"));
				callbackContext.sendPluginResult(new PluginResult(
						PluginResult.Status.OK));
			} catch (final JSONException e) {
				Log.e(LOG_PROV, LOG_NAME + "Error: "
						+ PluginResult.Status.JSON_EXCEPTION);
				e.printStackTrace();
				callbackContext.sendPluginResult(new PluginResult(
						PluginResult.Status.JSON_EXCEPTION));
			}
		}
	});
	return true;
}
 
Example #21
Source File: PluginManager.java    From CordovaYoutubeVideoPlayer with MIT License 6 votes vote down vote up
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
    if ("startup".equals(action)) {
        // The onPageStarted event of CordovaWebViewClient resets the queue of messages to be returned to javascript in response
        // to exec calls. Since this event occurs on the UI thread and exec calls happen on the WebCore thread it is possible
        // that onPageStarted occurs after exec calls have started happening on a new page, which can cause the message queue
        // to be reset between the queuing of a new message and its retrieval by javascript. To avoid this from happening,
        // javascript always sends a "startup" exec upon loading a new page which causes all future exec calls to happen on the UI
        // thread (and hence after onPageStarted) until there are no more pending exec calls remaining.
        numPendingUiExecs.getAndIncrement();
        ctx.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                numPendingUiExecs.getAndDecrement();
            }
        });
        return true;
    }
    return false;
}
 
Example #22
Source File: CodePush.java    From reacteu-app with MIT License 6 votes vote down vote up
private boolean execUpdateSuccess(CallbackContext callbackContext) {
    if (this.codePushPackageManager.isFirstRun()) {
        this.codePushPackageManager.saveFirstRunFlag();
        /* save reporting status for first install */
        try {
            String appVersion = Utilities.getAppVersionName(cordova.getActivity());
            codePushReportingManager.reportStatus(CodePushReportingManager.Status.STORE_VERSION, null, appVersion, mainWebView.getPreferences().getString(DEPLOYMENT_KEY_PREFERENCE, null), this.mainWebView);
        } catch (PackageManager.NameNotFoundException e) {
            // Should not happen unless the appVersion is not specified, in which case we can't report anything anyway.
            e.printStackTrace();
        }
    }

    if (this.codePushPackageManager.installNeedsConfirmation()) {
        /* save reporting status */
        CodePushPackageMetadata currentMetadata = this.codePushPackageManager.getCurrentPackageMetadata();
        codePushReportingManager.reportStatus(CodePushReportingManager.Status.UPDATE_CONFIRMED, currentMetadata.label, currentMetadata.appVersion, currentMetadata.deploymentKey, this.mainWebView);
    }

    this.codePushPackageManager.clearInstallNeedsConfirmation();
    this.cleanOldPackageSilently();
    callbackContext.success();

    return true;
}
 
Example #23
Source File: CameraPreview.java    From cordova-plugin-camera-preview with MIT License 6 votes vote down vote up
private boolean stopCamera(CallbackContext callbackContext) {
  if(webViewParent != null) {
    cordova.getActivity().runOnUiThread(new Runnable() {
      @Override
      public void run() {
        ((ViewGroup)webView.getView()).bringToFront();
        webViewParent = null;
      }
    });
  }

  if(this.hasView(callbackContext) == false){
    return true;
  }

  FragmentManager fragmentManager = cordova.getActivity().getFragmentManager();
  FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
  fragmentTransaction.remove(fragment);
  fragmentTransaction.commit();
  fragment = null;

  callbackContext.success();
  return true;
}
 
Example #24
Source File: WizPurchase.java    From cordova-plugin-wizpurchase with MIT License 6 votes vote down vote up
/**
 * Restore all Inventory products and purchases
 *
 * @param callbackContext Instance
 **/
private void restoreAllPurchases(CallbackContext callbackContext) throws JSONException {
	// Check if the Inventory is available
	if (mInventory != null) {
		// Get the list of owned items
		List<Purchase> purchaseList = mInventory.getAllPurchases();
		setPurchasesAsPending(purchaseList);
		JSONArray jsonPurchaseList = convertToJSONArray(purchaseList);
		// Return result
		callbackContext.success(jsonPurchaseList);
	} else {
		// Initialise the Plug-In
		cordova.getThreadPool().execute(new Runnable() {
			public void run() {
				List<String> skus = new ArrayList<String>();
				init(skus);
			}
		});
		// Retain the callback and wait
		mRestoreAllCbContext = callbackContext;
		retainCallBack(mRestoreAllCbContext);
	}
}
 
Example #25
Source File: NetworkManager.java    From ultimate-cordova-webview-app with MIT License 6 votes vote down vote up
/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return                  True if the action was valid, false otherwise.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("getConnectionInfo")) {
        this.connectionCallbackContext = callbackContext;
        NetworkInfo info = sockMan.getActiveNetworkInfo();
        String connectionType = "";
        try {
            connectionType = this.getConnectionInfo(info).get("type").toString();
        } catch (JSONException e) {
            LOG.d(LOG_TAG, e.getLocalizedMessage());
        }

        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    }
    return false;
}
 
Example #26
Source File: WizPurchase.java    From cordova-plugin-wizpurchase with MIT License 6 votes vote down vote up
/**
 * Get a list of purchases which have not been ended yet using finishPurchase
 *
 * @param callbackContext Instance
 **/
private void getPendingPurchases(CallbackContext callbackContext) throws JSONException {
	// Check if the Inventory is available
	if (mInventory != null) {
		// Get and return any previously purchased Items
		JSONArray jsonPurchaseList = new JSONArray();
		jsonPurchaseList = getPendingPurchases();
		// Return result
		callbackContext.success(jsonPurchaseList);
	} else {
		// Initialise the Plug-In
		cordova.getThreadPool().execute(new Runnable() {
			public void run() {
				List<String> skus = new ArrayList<String>();
				init(skus);
			}
		});
		// Retain the callback and wait
		mGetPendingCbContext = callbackContext;
		retainCallBack(mGetPendingCbContext);
	}
}
 
Example #27
Source File: SplashScreen.java    From AvI with MIT License 6 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("hide")) {
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                webView.postMessage("splashscreen", "hide");
            }
        });
    } else if (action.equals("show")) {
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                webView.postMessage("splashscreen", "show");
            }
        });
    } else {
        return false;
    }

    callbackContext.success();
    return true;
}
 
Example #28
Source File: SaveImage.java    From SaveImage with MIT License 5 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals(ACTION)) {
        saveImageToGallery(args, callbackContext);
        return true;
    } else {
        return false;
    }
}
 
Example #29
Source File: Share.java    From cordova-plugin-share with MIT License 5 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("share")) {
        String text = args.getString(0);
        String title = args.getString(1);
        String mimetype = args.getString(2);
        this.share(text, title, mimetype, callbackContext);
        return true;
    }
    return false;
}
 
Example #30
Source File: LocalNotification.java    From showCaseCordova with Apache License 2.0 5 votes vote down vote up
/**
 * If a notification with an ID is present.
 *
 * @param id
 *      Notification ID
 * @param command
 *      The callback context used when calling back into JavaScript.
 */
private void isPresent (int id, CallbackContext command) {
    boolean exist = getNotificationMgr().exist(id);

    PluginResult result = new PluginResult(
            PluginResult.Status.OK, exist);

    command.sendPluginResult(result);
}