org.apache.cordova.PluginResult Java Examples

The following examples show how to use org.apache.cordova.PluginResult. 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: NativeToJsMessageQueue.java    From phonegapbootcampsite with MIT License 6 votes vote down vote up
/**
 * Add a JavaScript statement to the list.
 */
public void addPluginResult(PluginResult result, String callbackId) {
    if (callbackId == null) {
        Log.e(LOG_TAG, "Got plugin result with no callbackId", new Throwable());
        return;
    }
    // Don't send anything if there is no result and there is no need to
    // clear the callbacks.
    boolean noResult = result.getStatus() == PluginResult.Status.NO_RESULT.ordinal();
    boolean keepCallback = result.getKeepCallback();
    if (noResult && keepCallback) {
        return;
    }
    JsMessage message = new JsMessage(result, callbackId);
    if (FORCE_ENCODE_USING_EVAL) {
        StringBuilder sb = new StringBuilder(message.calculateEncodedLength() + 50);
        message.encodeAsJsMessage(sb);
        message = new JsMessage(sb.toString());
    }

    enqueueMessage(message);
}
 
Example #2
Source File: NativeToJsMessageQueue.java    From reader with MIT License 6 votes vote down vote up
/**
 * Add a JavaScript statement to the list.
 */
public void addPluginResult(PluginResult result, String callbackId) {
    if (callbackId == null) {
        Log.e(LOG_TAG, "Got plugin result with no callbackId", new Throwable());
        return;
    }
    // Don't send anything if there is no result and there is no need to
    // clear the callbacks.
    boolean noResult = result.getStatus() == PluginResult.Status.NO_RESULT.ordinal();
    boolean keepCallback = result.getKeepCallback();
    if (noResult && keepCallback) {
        return;
    }
    JsMessage message = new JsMessage(result, callbackId);
    if (FORCE_ENCODE_USING_EVAL) {
        StringBuilder sb = new StringBuilder(message.calculateEncodedLength() + 50);
        message.encodeAsJsMessage(sb);
        message = new JsMessage(sb.toString());
    }

    enqueueMessage(message);
}
 
Example #3
Source File: AccelListener.java    From showCaseCordova with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the request.
 *
 * @param action        The action to execute.
 * @param args          The exec() arguments.
 * @param callbackId    The callback id used when calling back into JavaScript.
 * @return              Whether the action was valid.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("start")) {
        this.callbackContext = callbackContext;
        if (this.status != AccelListener.RUNNING) {
            // If not running, then this is an async call, so don't worry about waiting
            // We drop the callback onto our stack, call start, and let start and the sensor callback fire off the callback down the road
            this.start();
        }
    }
    else if (action.equals("stop")) {
        if (this.status == AccelListener.RUNNING) {
            this.stop();
        }
    } else {
      // Unsupported action
        return false;
    }

    PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT, "");
    result.setKeepCallback(true);
    callbackContext.sendPluginResult(result);
    return true;
}
 
Example #4
Source File: GeolocationPlugin.java    From cordova-plugin-baidu-geolocation with MIT License 6 votes vote down vote up
private boolean watchPosition(JSONObject options, int watchId, final CallbackContext callback) {
  Log.i(TAG, "监听位置变化");
  Context ctx = cordova.getActivity().getApplicationContext();
  PositionOptions positionOpts = new PositionOptions(options);
  BDGeolocation geolocation = new BDGeolocation(ctx);
  store.put(watchId, geolocation);
  return geolocation.watchPosition(positionOpts, new BDLocationListener() {
    @Override
    public void onReceiveLocation(BDLocation location) {
      JSONArray message = new MessageBuilder(location).build();
      PluginResult result = new PluginResult(PluginResult.Status.OK, message);
      result.setKeepCallback(true);
      callback.sendPluginResult(result);
    }
  });
}
 
Example #5
Source File: IntentShim.java    From darryncampbell-cordova-plugin-intent with MIT License 6 votes vote down vote up
private void startActivity(Intent i, boolean bExpectResult,  int requestCode, CallbackContext callbackContext) {

        if (i.resolveActivityInfo(this.cordova.getActivity().getPackageManager(), 0) != null)
        {
            if (bExpectResult)
            {
                cordova.setActivityResultCallback(this);
               this.cordova.getActivity().startActivityForResult(i, requestCode);
            }
            else
            {
                this.cordova.getActivity().startActivity(i);
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
            }
        }
        else
        {
            //  Return an error as there is no app to handle this intent
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
        }
    }
 
Example #6
Source File: HotCodePushPlugin.java    From cordova-hot-code-push with MIT License 6 votes vote down vote up
/**
 * Install update if any available.
 *
 * @param jsCallback callback where to send the result;
 *                   used, when installation os requested manually from JavaScript
 */
private void installUpdate(CallbackContext jsCallback) {
    if (!isPluginReadyForWork) {
        return;
    }

    ChcpError error = UpdatesInstaller.install(cordova.getActivity(), pluginInternalPrefs.getReadyForInstallationReleaseVersionName(), pluginInternalPrefs.getCurrentReleaseVersionName());
    if (error != ChcpError.NONE) {
        if (jsCallback != null) {
            PluginResult errorResult = PluginResultHelper.createPluginResult(UpdateInstallationErrorEvent.EVENT_NAME, null, error);
            jsCallback.sendPluginResult(errorResult);
        }

        return;
    }

    if (jsCallback != null) {
        installJsCallback = jsCallback;
    }
}
 
Example #7
Source File: HotCodePushPlugin.java    From cordova-hot-code-push with MIT License 6 votes vote down vote up
/**
 * Listener for the event that update is loaded and ready for the installation.
 *
 * @param event event information
 * @see EventBus
 * @see UpdateIsReadyToInstallEvent
 * @see UpdatesLoader
 */
@SuppressWarnings("unused")
@Subscribe
public void onEvent(UpdateIsReadyToInstallEvent event) {
    final ContentConfig newContentConfig = event.applicationConfig().getContentConfig();
    Log.d("CHCP", "Update is ready for installation: " + newContentConfig.getReleaseVersion());

    pluginInternalPrefs.setReadyForInstallationReleaseVersionName(newContentConfig.getReleaseVersion());
    pluginInternalPrefsStorage.storeInPreference(pluginInternalPrefs);

    PluginResult jsResult = PluginResultHelper.pluginResultFromEvent(event);

    // notify JS
    if (downloadJsCallback != null) {
        downloadJsCallback.sendPluginResult(jsResult);
        downloadJsCallback = null;
    }

    sendMessageToDefaultCallback(jsResult);

    // perform installation if allowed
    if (chcpXmlConfig.isAutoInstallIsAllowed() && newContentConfig.getUpdateTime() == UpdateTime.NOW) {
        installUpdate(null);
    }
}
 
Example #8
Source File: Fingerprint.java    From cordova-plugin-fingerprint-aio with MIT License 6 votes vote down vote up
private void executeAuthenticate(JSONArray args) {
    PluginError error = canAuthenticate();
    if (error != null) {
        sendError(error);
        return;
    }
    cordova.getActivity().runOnUiThread(() -> {
        mPromptInfoBuilder.parseArgs(args);
        Intent intent = new Intent(cordova.getActivity().getApplicationContext(), BiometricActivity.class);
        intent.putExtras(mPromptInfoBuilder.build().getBundle());
        this.cordova.startActivityForResult(this, intent, REQUEST_CODE_BIOMETRIC);
    });
    PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
    pluginResult.setKeepCallback(true);
    this.mCallbackContext.sendPluginResult(pluginResult);
}
 
Example #9
Source File: NativeToJsMessageQueue.java    From cordova-amazon-fireos with Apache License 2.0 6 votes vote down vote up
/**
 * Add a JavaScript statement to the list.
 */
public void addPluginResult(PluginResult result, String callbackId) {
    if (callbackId == null) {
        Log.e(LOG_TAG, "Got plugin result with no callbackId", new Throwable());
        return;
    }
    // Don't send anything if there is no result and there is no need to
    // clear the callbacks.
    boolean noResult = result.getStatus() == PluginResult.Status.NO_RESULT.ordinal();
    boolean keepCallback = result.getKeepCallback();
    if (noResult && keepCallback) {
        return;
    }
    JsMessage message = new JsMessage(result, callbackId);
    if (FORCE_ENCODE_USING_EVAL) {
        StringBuilder sb = new StringBuilder(message.calculateEncodedLength() + 50);
        message.encodeAsJsMessage(sb);
        message = new JsMessage(sb.toString());
    }

    enqueueMessage(message);
}
 
Example #10
Source File: BannerAd.java    From admob-plus with MIT License 6 votes vote down vote up
public static boolean executeHideAction(Action action, CallbackContext callbackContext) {
    plugin.cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            BannerAd bannerAd = (BannerAd) action.getAd();
            if (bannerAd != null) {
                bannerAd.hide();
            }

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

    return true;
}
 
Example #11
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")) {
            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 #12
Source File: SendingTask.java    From WebSocket-for-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(String rawArgs, CallbackContext ctx) {
    try {
        String args = new JSONArray(rawArgs).getString(0);
        Connection conn = _map.get(Integer.parseInt(args.substring(0, 8), 16));

        if (conn != null) {
            if (args.charAt(8) == '1') {
                byte[] binary = Base64.decode(args.substring(args.indexOf(',') + 1), Base64.NO_WRAP);
                conn.sendMessage(binary, 0, binary.length);
            } else {
                conn.sendMessage(args.substring(9));
            }
        } else {
        }
    } catch (Exception e) {
        if (!ctx.isFinished()) {
            PluginResult result = new PluginResult(Status.ERROR);
            result.setKeepCallback(true);
            ctx.sendPluginResult(result);
        }
    }
}
 
Example #13
Source File: NativeToJsMessageQueue.java    From phonegap-plugin-loading-spinner with Apache License 2.0 6 votes vote down vote up
void encodeAsJsMessage(StringBuilder sb) {
    if (pluginResult == null) {
        sb.append(jsPayloadOrCallbackId);
    } else {
        int status = pluginResult.getStatus();
        boolean success = (status == PluginResult.Status.OK.ordinal()) || (status == PluginResult.Status.NO_RESULT.ordinal());
        sb.append("cordova.callbackFromNative('")
          .append(jsPayloadOrCallbackId)
          .append("',")
          .append(success)
          .append(",")
          .append(status)
          .append(",[")
          .append(pluginResult.getMessage())
          .append("],")
          .append(pluginResult.getKeepCallback())
          .append(");");
    }
}
 
Example #14
Source File: SMSReceive.java    From cordova-plugin-sms-receive with MIT License 5 votes vote down vote up
private PluginResult startWatch(CallbackContext callbackContext) {
	Log.d(LOG_TAG, ACTION_START_WATCH);
	if (this.mReceiver == null) {
		this.createIncomingSMSReceiver();
	}
	if (callbackContext != null) {
		callbackContext.success();
	}
	return null;
}
 
Example #15
Source File: WizPurchase.java    From cordova-plugin-wizpurchase with MIT License 5 votes vote down vote up
/**
 * Retain a Callback
 *
 * @param target CallBack Instance to retain
 * @param source Source Callback instance
 **/
private void retainCallBack(CallbackContext cb) {
	// Retain callback and wait
	PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
	result.setKeepCallback(true);
	cb.sendPluginResult(result);
}
 
Example #16
Source File: espSmartconfig.java    From cordova-plugin-smartconfig with Apache License 2.0 5 votes vote down vote up
@Override
public void onEsptouchResultAdded(final IEsptouchResult result) {
    String text = "bssid="+ result.getBssid()+",InetAddress="+result.getInetAddress().getHostAddress();
    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, text);
    pluginResult.setKeepCallback(true);           // keep callback after this call
    //receivingCallbackContext.sendPluginResult(pluginResult);    //modified by lianghuiyuan
}
 
Example #17
Source File: FileUtils.java    From keemob with MIT License 5 votes vote down vote up
private void threadhelper(final FileOp f, final String rawArgs, final CallbackContext callbackContext){
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            try {
                JSONArray args = new JSONArray(rawArgs);
                f.run(args);
            } catch ( Exception e) {
                if( e instanceof EncodingException){
                    callbackContext.error(FileUtils.ENCODING_ERR);
                } else if(e instanceof FileNotFoundException) {
                    callbackContext.error(FileUtils.NOT_FOUND_ERR);
                } else if(e instanceof FileExistsException) {
                    callbackContext.error(FileUtils.PATH_EXISTS_ERR);
                } else if(e instanceof NoModificationAllowedException ) {
                    callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
                } else if(e instanceof InvalidModificationException ) {
                    callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
                } else if(e instanceof MalformedURLException ) {
                    callbackContext.error(FileUtils.ENCODING_ERR);
                } else if(e instanceof IOException ) {
                    callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
                } else if(e instanceof EncodingException ) {
                    callbackContext.error(FileUtils.ENCODING_ERR);
                } else if(e instanceof TypeMismatchException ) {
                    callbackContext.error(FileUtils.TYPE_MISMATCH_ERR);
                } else if(e instanceof JSONException ) {
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                } else if (e instanceof SecurityException) {
                    callbackContext.error(FileUtils.SECURITY_ERR);
                } else {
                    e.printStackTrace();
                	callbackContext.error(FileUtils.UNKNOWN_ERR);
                }
            }
        }
    });
}
 
Example #18
Source File: IMEIPlugin.java    From cordova-plugin-imei with MIT License 5 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    if (action.equals("get")) {
        TelephonyManager telephonyManager = (TelephonyManager)this.cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
        result = telephonyManager.getDeviceId();
    }
    else {
        status = PluginResult.Status.INVALID_ACTION;
    }
    callbackContext.sendPluginResult(new PluginResult(status, result));
    return true;
}
 
Example #19
Source File: Utils.java    From cordova-plugin-iroot with MIT License 5 votes vote down vote up
/**
 * Helper function that logs the error and then calls the error callback.
 */
public static PluginResult getPluginResultError(final String from, final Throwable e) {
    String message = String.format("[%s] Error: %s", from, e.getMessage());

    LOG.e(Constants.LOG_TAG, message, e);

    return new PluginResult(Status.ERROR, message);
}
 
Example #20
Source File: CellLocationController.java    From cordova-plugin-advanced-geolocation with Apache License 2.0 5 votes vote down vote up
private static void sendCallback(PluginResult.Status status, String message){
    if(!Thread.currentThread().isInterrupted()){
        final PluginResult result = new PluginResult(status, message);
        result.setKeepCallback(true);
        _callbackContext.sendPluginResult(result);
    }
}
 
Example #21
Source File: Sms.java    From cordova-sms-plugin with MIT License 5 votes vote down vote up
private boolean sendSMS() {
	cordova.getThreadPool().execute(new Runnable() {
		@Override
		public void run() {
			try {
				//parsing arguments
				String separator = ";";
				if (android.os.Build.MANUFACTURER.equalsIgnoreCase("Samsung")) {
					// See http://stackoverflow.com/questions/18974898/send-sms-through-intent-to-multiple-phone-numbers/18975676#18975676
					separator = ",";
				}
				String phoneNumber = args.getJSONArray(0).join(separator).replace("\"", "");
				String message = args.getString(1);
				String method = args.getString(2);
				boolean replaceLineBreaks = Boolean.parseBoolean(args.getString(3));

				// replacing \n by new line if the parameter replaceLineBreaks is set to true
				if (replaceLineBreaks) {
					message = message.replace("\\n", System.getProperty("line.separator"));
				}
				if (!checkSupport()) {
					callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "SMS not supported on this platform"));
					return;
				}
				if (method.equalsIgnoreCase("INTENT")) {
					invokeSMSIntent(phoneNumber, message);
					// always passes success back to the app
					callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
				} else {
					send(callbackContext, phoneNumber, message);
				}
				return;
			} catch (JSONException ex) {
				callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
			}
		}
	});
	return true;
}
 
Example #22
Source File: CameraPreview.java    From cordova-plugin-camera-preview with MIT License 5 votes vote down vote up
public void onBackButton() {
  if(tapBackButtonContext == null) {
    return;
  }

  Log.d(TAG, "Back button tapped, notifying");

  PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "Back button pressed");
  tapBackButtonContext.sendPluginResult(pluginResult);
}
 
Example #23
Source File: InAppBrowser.java    From jpHolo with MIT License 5 votes vote down vote up
/**
 * Create a new plugin result and send it back to JavaScript
 *
 * @param obj a JSONObject contain event payload information
 * @param status the status code to return to the JavaScript environment
 */    
private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
    if (callbackContext != null) {
        PluginResult result = new PluginResult(status, obj);
        result.setKeepCallback(keepCallback);
        callbackContext.sendPluginResult(result);
        if (!keepCallback) {
            callbackContext = null;
        }
    }
}
 
Example #24
Source File: HotCodePushPlugin.java    From cordova-hot-code-push with MIT License 5 votes vote down vote up
/**
 * Get information about app and web versions.
 *
 * @param callback callback where to send the result
 */
private void jsGetVersionInfo(final CallbackContext callback) {
    final Context context = cordova.getActivity();
    final Map<String, Object> data = new HashMap<String, Object>();
    data.put("currentWebVersion", pluginInternalPrefs.getCurrentReleaseVersionName());
    data.put("readyToInstallWebVersion", pluginInternalPrefs.getReadyForInstallationReleaseVersionName());
    data.put("previousWebVersion", pluginInternalPrefs.getPreviousReleaseVersionName());
    data.put("appVersion", VersionHelper.applicationVersionName(context));
    data.put("buildVersion", VersionHelper.applicationVersionCode(context));

    final PluginResult pluginResult = PluginResultHelper.createPluginResult(null, data, null);
    callback.sendPluginResult(pluginResult);
}
 
Example #25
Source File: CallbackContext.java    From a2cardboard with Apache License 2.0 5 votes vote down vote up
public void sendPluginResult(PluginResult pluginResult) {
    synchronized (this) {
        if (finished) {
            Log.w(LOG_TAG, "Attempted to send a second callback for ID: " + callbackId + "\nResult was: " + pluginResult.getMessage());
            return;
        } else {
            finished = !pluginResult.getKeepCallback();
        }
    }
    webView.sendPluginResult(pluginResult, callbackId);
}
 
Example #26
Source File: InAppBrowser.java    From reader with MIT License 5 votes vote down vote up
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    super.onReceivedError(view, errorCode, description, failingUrl);
    
    try {
        JSONObject obj = new JSONObject();
        obj.put("type", LOAD_ERROR_EVENT);
        obj.put("url", failingUrl);
        obj.put("code", errorCode);
        obj.put("message", description);
    
        sendUpdate(obj, true, PluginResult.Status.ERROR);
    } catch (JSONException ex) {
        Log.d(LOG_TAG, "Should never happen");
    }
}
 
Example #27
Source File: NativeToJsMessageQueue.java    From cordova-amazon-fireos with Apache License 2.0 5 votes vote down vote up
JsMessage(PluginResult pluginResult, String callbackId) {
    if (callbackId == null || pluginResult == null) {
        throw new NullPointerException();
    }
    jsPayloadOrCallbackId = callbackId;
    this.pluginResult = pluginResult;
}
 
Example #28
Source File: FileTransfer.java    From reader with MIT License 5 votes vote down vote up
/**
 * Abort an ongoing upload or download.
 */
private void abort(String objectId) {
    final RequestContext context;
    synchronized (activeRequests) {
        context = activeRequests.remove(objectId);
    }
    if (context != null) {
        // Closing the streams can block, so execute on a background thread.
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                synchronized (context) {
                    File file = context.targetFile;
                    if (file != null) {
                        file.delete();
                    }
                    // Trigger the abort callback immediately to minimize latency between it and abort() being called.
                    JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1, null);
                    context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error));
                    context.aborted = true;
                    if (context.connection != null) {
                        context.connection.disconnect();
                    }
                }
            }
        });
    }
}
 
Example #29
Source File: NativeToJsMessageQueue.java    From reader with MIT License 5 votes vote down vote up
int calculateEncodedLength() {
    if (pluginResult == null) {
        return jsPayloadOrCallbackId.length() + 1;
    }
    int statusLen = String.valueOf(pluginResult.getStatus()).length();
    int ret = 2 + statusLen + 1 + jsPayloadOrCallbackId.length() + 1;
    switch (pluginResult.getMessageType()) {
        case PluginResult.MESSAGE_TYPE_BOOLEAN: // f or t
        case PluginResult.MESSAGE_TYPE_NULL: // N
            ret += 1;
            break;
        case PluginResult.MESSAGE_TYPE_NUMBER: // n
            ret += 1 + pluginResult.getMessage().length();
            break;
        case PluginResult.MESSAGE_TYPE_STRING: // s
            ret += 1 + pluginResult.getStrMessage().length();
            break;
        case PluginResult.MESSAGE_TYPE_BINARYSTRING:
            ret += 1 + pluginResult.getMessage().length();
            break;
        case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
            ret += 1 + pluginResult.getMessage().length();
            break;
        case PluginResult.MESSAGE_TYPE_JSON:
        default:
            ret += pluginResult.getMessage().length();
    }
    return ret;
}
 
Example #30
Source File: InAppBrowser.java    From reader with MIT License 5 votes vote down vote up
/**
 * Create a new plugin result and send it back to JavaScript
 *
 * @param obj a JSONObject contain event payload information
 * @param status the status code to return to the JavaScript environment
 */    
private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
    if (callbackContext != null) {
        PluginResult result = new PluginResult(status, obj);
        result.setKeepCallback(keepCallback);
        callbackContext.sendPluginResult(result);
        if (!keepCallback) {
            callbackContext = null;
        }
    }
}