类org.apache.cordova.PluginResult源码实例Demo

下面列出了怎么用org.apache.cordova.PluginResult的API类实例代码及写法,或者点击链接到github查看源代码。

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);
    }
  });
}
 
/**
 * 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);
}
 
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(");");
    }
}
 
源代码4 项目: reader   文件: FileTransfer.java
@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;
}
 
源代码5 项目: cordova-hot-code-push   文件: HotCodePushPlugin.java
/**
 * 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);
    }
}
 
/**
 * 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);
}
 
源代码7 项目: admob-plus   文件: BannerAd.java
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;
}
 
源代码8 项目: reader   文件: NativeToJsMessageQueue.java
/**
 * 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);
}
 
源代码9 项目: showCaseCordova   文件: AccelListener.java
/**
 * 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;
}
 
源代码10 项目: cordova-hot-code-push   文件: HotCodePushPlugin.java
/**
 * 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;
    }
}
 
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);
}
 
源代码12 项目: WebSocket-for-Android   文件: SendingTask.java
@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);
        }
    }
}
 
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));
        }
    }
 
源代码14 项目: MFileChooser   文件: FileChooser.java
public void chooseFile(CallbackContext callbackContext) {

        // type and title should be configurable
    	Context context=this.cordova.getActivity().getApplicationContext();
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setClass(context,FileChooserActivity.class);
        
        Intent chooser = Intent.createChooser(intent, "Select File");
        cordova.startActivityForResult(this, chooser, PICK_FILE_REQUEST);
        
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callback = callbackContext;
        callbackContext.sendPluginResult(pluginResult);
    }
 
源代码15 项目: cordova-plugin-intent   文件: IntentPlugin.java
/**
 * Send a JSON representation of the cordova intent back to the caller
 *
 * @param data
 * @param context
 */
public boolean getCordovaIntent (final JSONArray data, final CallbackContext context) {
    if(data.length() != 0) {
        context.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
        return false;
    }

    Intent intent = cordova.getActivity().getIntent();
    context.sendPluginResult(new PluginResult(PluginResult.Status.OK, getIntentJson(intent)));
    return true;
}
 
源代码16 项目: reacteu-app   文件: FileTransfer.java
/**
 * Abort an ongoing upload or download.
 */
private void abort(String objectId) {
    final RequestContext context;
    synchronized (activeRequests) {
        context = activeRequests.remove(objectId);
    }
    if (context != null) {
        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);
        synchronized (context) {
            context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error));
            context.aborted = true;
        }
        // Closing the streams can block, so execute on a background thread.
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                synchronized (context) {
                    safeClose(context.currentInputStream);
                    safeClose(context.currentOutputStream);
                }
            }
        });
    }
}
 
源代码17 项目: cordova-plugin-iroot   文件: Utils.java
/**
 * 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);
}
 
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);
    }
}
 
源代码19 项目: cordova-hot-code-push   文件: HotCodePushPlugin.java
/**
 * Listener for event that an update is about to begin
 *
 * @param event event information
 * @see EventBus
 * @see BeforeInstallEvent
 * @see UpdatesLoader
 */
@SuppressWarnings("unused")
@Subscribe
public void onEvent(BeforeInstallEvent event) {
    Log.d("CHCP", "Dispatching Before install event");

    PluginResult jsResult = PluginResultHelper.pluginResultFromEvent(event);

    sendMessageToDefaultCallback(jsResult);
}
 
源代码20 项目: wildfly-samples   文件: NativeToJsMessageQueue.java
JsMessage(PluginResult pluginResult, String callbackId) {
    if (callbackId == null || pluginResult == null) {
        throw new NullPointerException();
    }
    jsPayloadOrCallbackId = callbackId;
    this.pluginResult = pluginResult;
}
 
源代码21 项目: bluemix-parking-meter   文件: CallbackContext.java
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);
}
 
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(",[");
        switch (pluginResult.getMessageType()) {
            case PluginResult.MESSAGE_TYPE_BINARYSTRING:
                sb.append("atob('")
                  .append(pluginResult.getMessage())
                  .append("')");
                break;
            case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
                sb.append("cordova.require('cordova/base64').toArrayBuffer('")
                  .append(pluginResult.getMessage())
                  .append("')");
                break;
            default:
            sb.append(pluginResult.getMessage());
        }
        sb.append("],")
          .append(pluginResult.getKeepCallback())
          .append(");");
    }
}
 
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);
}
 
源代码24 项目: countly-sdk-cordova   文件: CallbackContext.java
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);
}
 
源代码25 项目: cordova-plugin-sms-receive   文件: SMSReceive.java
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;
}
 
@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
}
 
源代码27 项目: cordova-sms-plugin   文件: Sms.java
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;
}
 
源代码28 项目: keemob   文件: FileUtils.java
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);
                }
            }
        }
    });
}
 
源代码29 项目: jpHolo   文件: InAppBrowser.java
/**
 * 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;
        }
    }
}
 
源代码30 项目: a2cardboard   文件: CallbackContext.java
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);
}
 
 类所在包