下面列出了怎么用org.apache.cordova.CordovaArgs的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
private boolean execIsFirstRun(CordovaArgs args, CallbackContext callbackContext) {
try {
boolean isFirstRun = false;
String packageHash = args.getString(0);
CodePushPackageMetadata currentPackageMetadata = codePushPackageManager.getCurrentPackageMetadata();
if (null != currentPackageMetadata) {
/* This is the first run for a package if we just updated, and the current package hash matches the one provided. */
isFirstRun = (null != packageHash
&& !packageHash.isEmpty()
&& packageHash.equals(currentPackageMetadata.packageHash)
&& didUpdate);
}
callbackContext.success(isFirstRun ? 1 : 0);
} catch (JSONException e) {
callbackContext.error("Invalid package hash. " + e.getMessage());
}
return true;
}
private boolean execRestartApplication(CordovaArgs args, CallbackContext callbackContext) {
try {
/* check if we have a deployed package already */
CodePushPackageMetadata deployedPackageMetadata = this.codePushPackageManager.getCurrentPackageMetadata();
if (deployedPackageMetadata != null) {
callbackContext.success();
didStartApp = false;
onStart();
} else {
final String configLaunchUrl = this.getConfigLaunchUrl();
if (!this.pluginDestroyed) {
callbackContext.success();
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
navigateToURL(configLaunchUrl);
}
});
}
}
} catch (Exception e) {
callbackContext.error("An error occurred while restarting the application." + e.getMessage());
}
return true;
}
private boolean execPreInstall(CordovaArgs args, CallbackContext callbackContext) {
/* check if package is valid */
try {
final String startLocation = args.getString(0);
File startPage = this.getStartPageForPackage(startLocation);
if (startPage != null) {
/* start page exists */
callbackContext.success();
} else {
callbackContext.error("Could not get the package start page");
}
} catch (Exception e) {
callbackContext.error("Could not get the package start page");
}
return true;
}
@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
boolean cmdProcessed = true;
if (JSAction.INIT.equals(action)) {
jsInit(callbackContext);
} else if (JSAction.FETCH_UPDATE.equals(action)) {
jsFetchUpdate(callbackContext, args);
} else if (JSAction.INSTALL_UPDATE.equals(action)) {
jsInstallUpdate(callbackContext);
} else if (JSAction.CONFIGURE.equals(action)) {
jsSetPluginOptions(args, callbackContext);
} else if (JSAction.REQUEST_APP_UPDATE.equals(action)) {
jsRequestAppUpdate(args, callbackContext);
} else if (JSAction.IS_UPDATE_AVAILABLE_FOR_INSTALLATION.equals(action)) {
jsIsUpdateAvailableForInstallation(callbackContext);
} else if (JSAction.GET_VERSION_INFO.equals(action)) {
jsGetVersionInfo(callbackContext);
} else {
cmdProcessed = false;
}
return cmdProcessed;
}
/**
* Set plugin options. Method is called from JavaScript.
*
* @param arguments arguments from JavaScript
* @param callback callback where to send result
*/
@Deprecated
private void jsSetPluginOptions(CordovaArgs arguments, CallbackContext callback) {
if (!isPluginReadyForWork) {
sendPluginNotReadyToWork("", callback);
return;
}
try {
JSONObject jsonObject = (JSONObject) arguments.get(0);
chcpXmlConfig.mergeOptionsFromJs(jsonObject);
// TODO: store them somewhere?
} catch (JSONException e) {
Log.d("CHCP", "Failed to process plugin options, received from JS.", e);
}
callback.success();
}
/**
* Show dialog with request to update the application through the Google Play.
*
* @param arguments arguments from JavaScript
* @param callback callback where to send result
*/
private void jsRequestAppUpdate(final CordovaArgs arguments, final CallbackContext callback) {
if (!isPluginReadyForWork) {
sendPluginNotReadyToWork("", callback);
return;
}
String msg = null;
try {
msg = (String) arguments.get(0);
} catch (JSONException e) {
Log.d("CHCP", "Dialog message is not set", e);
}
if (TextUtils.isEmpty(msg)) {
return;
}
final String storeURL = appConfigStorage.loadFromFolder(fileStructure.getWwwFolder()).getStoreUrl();
new AppUpdateRequestDialog(cordova.getActivity(), msg, storeURL, callback).show();
}
public void initialize(CordovaArgs args, final CallbackContext ctx) throws JSONException {
service.addPurchaseObserver(this);
service.init(new InAppService.InitCompletion() {
@Override
public void onInit(Error error) {
JSONObject data = new JSONObject();
try {
data.put("products", InAppServicePlugin.this.productsToJSON(service.getProducts()));
data.put("canPurchase", service.canPurchase());
if (error != null) {
data.put("error", errorToJSON(error));
}
}
catch (JSONException e) {
e.printStackTrace();
}
ctx.sendPluginResult(new PluginResult(Status.OK, data));
}
});
}
public void fetchProducts(CordovaArgs args, final CallbackContext ctx) {
JSONArray array = args.optJSONArray(0);
if (array == null) {
ctx.sendPluginResult(new PluginResult(Status.INVALID_ACTION, "Invalid argument"));
return;
}
ArrayList<String> productIds = new ArrayList<String>();
for (int i = 0; i < array.length(); ++i) {
productIds.add(array.optString(i, "empty"));
}
service.fetchProducts(productIds, new InAppService.FetchCallback() {
@Override
public void onComplete(final List<InAppProduct> products, Error error) {
if (error != null) {
ctx.sendPluginResult(new PluginResult(Status.ERROR, errorToJSON(error)));
}
else {
ctx.sendPluginResult(new PluginResult(Status.OK, productsToJSON(products)));
}
}
});
}
public void consume(CordovaArgs args, final CallbackContext ctx) {
String productId = args.optString(0);
if (productId == null) {
ctx.sendPluginResult(new PluginResult(Status.ERROR, "Invalid argument"));
return;
}
int quantity = args.optInt(1);
if (quantity < 1) {
quantity = 1;
}
service.consume(productId, quantity, new InAppService.ConsumeCallback() {
@Override
public void onComplete(int consumed, Error error) {
if (error != null) {
ctx.sendPluginResult(new PluginResult(Status.ERROR, errorToJSON(error)));
}
else {
ctx.sendPluginResult(new PluginResult(Status.OK, consumed));
}
}
});
}
public void setValidationHandler(CordovaArgs args, final CallbackContext ctx) {
boolean noValidation = args.optBoolean(0);
if (noValidation) {
service.setValidationHandler(null);
return;
}
service.setValidationHandler(new InAppService.ValidationHandler() {
@Override
public void onValidate(String receipt, String productId, ValidationCompletion completion) {
int completionId = validationIndex++;
validationCompletions.put(completionId, completion);
JSONArray array = new JSONArray();
array.put(receipt);
array.put(productId);
array.put(completionId);
PluginResult result = new PluginResult(Status.OK, array);
result.setKeepCallback(true);
ctx.sendPluginResult(result);
}
});
}
@Override
public boolean execute(String action, CordovaArgs args,
CallbackContext callbackContext) throws JSONException {
final String ACTION_ONCONNECT = "onConnect";
final String ACTION_ONDATARECEIVED = "onDataReceived";
final String ACTION_ONERROR = "onError";
final String ACTION_SENDDATA = "sendData";
if (ACTION_ONCONNECT.equals(action))
onConnect(callbackContext);
else if (ACTION_ONDATARECEIVED.equals(action))
onDataReceived(args, callbackContext);
else if (ACTION_ONERROR.equals(action))
onError(args, callbackContext);
else if (ACTION_SENDDATA.equals(action))
sendData(args, callbackContext);
else
return false;
return true;
}
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());
}
}
@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;
}
@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;
}
@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;
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) {
PluginResult result = new PluginResult(PluginResult.Status.OK, "");
try {
if (action.equals("start")) {
this.startActivity(args.getString(0));
callbackContext.sendPluginResult(result);
callbackContext.success();
return true;
}
} catch (JSONException e) {
result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, "JSON Exception");
callbackContext.sendPluginResult(result);
return false;
}
return false;
}
@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;
}
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) {
if ("getServerURL".equals(action)) {
this.returnStringPreference("codepushserverurl", callbackContext);
return true;
} else if ("getDeploymentKey".equals(action)) {
this.returnStringPreference(DEPLOYMENT_KEY_PREFERENCE, callbackContext);
return true;
} else if ("getNativeBuildTime".equals(action)) {
return execGetNativeBuildTime(callbackContext);
} else if ("getAppVersion".equals(action)) {
return execGetAppVersion(callbackContext);
} else if ("getBinaryHash".equals(action)) {
return execGetBinaryHash(callbackContext);
} else if ("preInstall".equals(action)) {
return execPreInstall(args, callbackContext);
} else if ("install".equals(action)) {
return execInstall(args, callbackContext);
} else if ("updateSuccess".equals(action)) {
return execUpdateSuccess(callbackContext);
} else if ("restartApplication".equals(action)) {
return execRestartApplication(args, callbackContext);
} else if ("isPendingUpdate".equals(action)) {
return execIsPendingUpdate(args, callbackContext);
} else if ("isFailedUpdate".equals(action)) {
return execIsFailedUpdate(args, callbackContext);
} else if ("isFirstRun".equals(action)) {
return execIsFirstRun(args, callbackContext);
} else {
return false;
}
}
private boolean execIsPendingUpdate(CordovaArgs args, CallbackContext callbackContext) {
try {
InstallOptions pendingInstall = this.codePushPackageManager.getPendingInstall();
callbackContext.success((pendingInstall != null) ? 1 : 0);
} catch (Exception e) {
callbackContext.error("An error occurred. " + e.getMessage());
}
return true;
}
private boolean execIsFailedUpdate(CordovaArgs args, CallbackContext callbackContext) {
try {
final String packageHash = args.getString(0);
boolean isFailedUpdate = this.codePushPackageManager.isFailedUpdate(packageHash);
callbackContext.success(isFailedUpdate ? 1 : 0);
} catch (JSONException e) {
callbackContext.error("Could not read the package hash: " + e.getMessage());
}
return true;
}
/**
* 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.
*/
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
Log.v(TAG, "Executing action: " + action);
final Activity activity = this.cordova.getActivity();
final Window window = activity.getWindow();
if ("_ready".equals(action)) {
boolean statusBarVisible = (window.getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0;
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, statusBarVisible));
}
if ("show".equals(action)) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
});
return true;
}
if ("hide".equals(action)) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
});
return true;
}
return false;
}
/**
* Check for update.
* Method is called from JS side.
*
* @param callback js callback
*/
private void jsFetchUpdate(CallbackContext callback, CordovaArgs args) {
if (!isPluginReadyForWork) {
sendPluginNotReadyToWork(UpdateDownloadErrorEvent.EVENT_NAME, callback);
return;
}
FetchUpdateOptions fetchOptions = null;
try {
fetchOptions = new FetchUpdateOptions(args.optJSONObject(0));
} catch (JSONException ignored) {
}
fetchUpdate(callback, fetchOptions);
}
@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
try
{
Method method = InAppServicePlugin.class.getDeclaredMethod(action, CordovaArgs.class, CallbackContext.class);
method.invoke(this, args, callbackContext);
return true;
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void productforId(CordovaArgs args, CallbackContext ctx) {
String productId = args.optString(0);
InAppProduct product = null;
if (productId != null) {
product = service.productForId(productId);
}
if (product!= null) {
ctx.sendPluginResult(new PluginResult(Status.OK, product.toJSON()));
}
else {
ctx.sendPluginResult(new PluginResult(Status.OK));
}
}
public void restorePurchases(CordovaArgs args, final CallbackContext ctx) {
service.restorePurchases(new InAppService.RestoreCallback() {
@Override
public void onComplete(Error error) {
if (error != null) {
ctx.sendPluginResult(new PluginResult(Status.ERROR, errorToJSON(error)));
}
else {
ctx.sendPluginResult(new PluginResult(Status.OK));
}
}
});
}
public void validationCompletion(CordovaArgs args, CallbackContext ctx) {
int completionId = args.optInt(0);
boolean validationResult = args.optBoolean(1);
InAppService.ValidationCompletion completion = validationCompletions.get(completionId);
if (completion != null) {
Error error = null;
if (!validationResult) {
error = new Error(0, "Custom validation rejected purchase");
}
completion.finishValidation(error);
validationCompletions.remove(completionId);
}
}
private void onDataReceived(final CordovaArgs args,
final CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "onDataReceived");
String connectionId = args.getString(0);
WearConnection connection = connections.get(connectionId);
if (connection != null) {
connection.addDataListener(callbackContext);
} else {
callbackContext.error("Invalid connection handle");
}
}
private void onError(final CordovaArgs args,
final CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "onError");
String connectionId = args.getString(0);
WearConnection connection = connections.get(connectionId);
if (connection != null) {
connection.addErrorListener(callbackContext);
} else {
callbackContext.error("Invalid connection handle");
}
}
/**
* 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.
*/
@Override
public boolean execute(final String action, final CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
Log.v(TAG, "Executing action: " + action);
final Activity activity = this.cordova.getActivity();
final Window window = activity.getWindow();
if ("_ready".equals(action)) {
boolean statusBarVisible = (window.getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0;
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, statusBarVisible));
}
if ("show".equals(action)) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
});
return true;
}
if ("hide".equals(action)) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
});
return true;
}
if ("backgroundColorByHexString".equals(action)) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
setStatusBarBackgroundColor(args.getString(0));
} catch (JSONException ignore) {
Log.e(TAG, "Invalid hexString argument, use f.i. '#777777'");
}
}
});
return true;
}
return false;
}