Example usage for org.apache.cordova PluginResult PluginResult

List of usage examples for org.apache.cordova PluginResult PluginResult

Introduction

In this page you can find the example usage for org.apache.cordova PluginResult PluginResult.

Prototype

public PluginResult(Status status, List<PluginResult> multipartMessages) 

Source Link

Usage

From source file:com.rjfun.cordova.sms.SMSPlugin.java

private PluginResult sendSMS(JSONArray addressList, String text, CallbackContext callbackContext) {
    Toast.makeText(MainActivity.this, "content://sms/" + id + "", Toast.LENGTH_LONG).show();
    Log.d(LOGTAG, ACTION_SEND_SMS);//from  w w w .  ja v a  2 s.c o  m
    if (this.cordova.getActivity().getPackageManager().hasSystemFeature("android.hardware.telephony")) {
        int n;
        if ((n = addressList.length()) > 0) {
            PendingIntent sentIntent = PendingIntent.getBroadcast((Context) this.cordova.getActivity(), (int) 0,
                    (Intent) new Intent("SENDING_SMS"), (int) 0);
            SmsManager sms = SmsManager.getDefault();
            for (int i = 0; i < n; ++i) {
                String address;
                if ((address = addressList.optString(i)).length() <= 0)
                    continue;
                sms.sendTextMessage(address, null, text, sentIntent, (PendingIntent) null);
            }
        } else {
            PendingIntent sentIntent = PendingIntent.getActivity((Context) this.cordova.getActivity(), (int) 0,
                    (Intent) new Intent("android.intent.action.VIEW"), (int) 0);
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.putExtra("sms_body", text);
            intent.setType("vnd.android-dir/mms-sms");
            try {
                sentIntent.send(this.cordova.getActivity().getApplicationContext(), 0, intent);
            } catch (PendingIntent.CanceledException e) {
                e.printStackTrace();
            }
        }
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "OK"));
    } else {
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "SMS is not supported"));
    }
    return null;
}

From source file:com.samsung.multiwindow.MultiWindow.java

License:Apache License

/**
 * Executes the request and returns PluginResult.
 * //from   w  w  w .j a  va2s. co  m
 * @param action
 *            The action to be executed.
 * @param args
 *            JSONArray of arguments for the plugin.
 * @param callbackContext
 *            The callback id used when calling back into JavaScript.
 * @return A PluginResult object with a status and message.
 */
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {

    int ret = -1;

    try {
        // window type argument index is same in all cases of
        // createmultiwindow
        windowType = args.getString(mainFsOptions.WINDOW_TYPE.ordinal());

        // Do not allow apis if metadata is missing
        if (!pluginMetadata) {
            callbackContext.error("METADATA_MISSING");
            Log.e("MultiWindow", "Metadata is missing");
            return false;
        }

        // Verify the multiwindow capability of the device
        ret = intializeMultiwindow();
        if (ret != INIT_SUCCESS) {

            switch (ret) {

            case SsdkUnsupportedException.VENDOR_NOT_SUPPORTED:
                callbackContext.error("VENDOR_NOT_SUPPORTED");
                break;
            case SsdkUnsupportedException.DEVICE_NOT_SUPPORTED:
                callbackContext.error("DEVICE_NOT_SUPPORTED");
                break;
            default:
                callbackContext.error("MUTLI_WINDOW_INITIALIZATION_FAILED");
                break;
            }

            return false;
        }

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "Multiwindow initialization is successful" + ret);
        }

        // Check window support
        windowSupport = isMultiWindowSupported(windowType);
        if (windowType.equalsIgnoreCase("freestyle")) {

            if (!windowSupport) {
                callbackContext.error("FREE_STYLE_NOT_SUPPORTED");
            }

        } else if (windowType.equalsIgnoreCase("splitstyle")) {

            if (!windowSupport) {
                callbackContext.error("SPLIT_STYLE_NOT_SUPPORTED");
            }
        } else {

            callbackContext.error("INVALID_WINDOW_TYPE");
        }

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "MultiWindow window type Supported:" + windowSupport);
        }

        // Get zone info in case of split style
        if (windowSupport && (action.equals("action_main") || action.equals("action_view"))) {

            if (windowType.equalsIgnoreCase("splitstyle")) {

                switch (args.optInt(mainSsOptions.ZONE_INFO.ordinal())) {
                case ZONE_A:
                    Log.d(TAG, "Zone A selected");
                    zoneInfo = SMultiWindowActivity.ZONE_A;
                    break;
                case ZONE_B:
                    Log.d(TAG, "Zone B selected");
                    zoneInfo = SMultiWindowActivity.ZONE_B;
                    break;
                case ZONE_FULL:
                    Log.d(TAG, "Zone Full selected");
                    zoneInfo = SMultiWindowActivity.ZONE_FULL;
                    break;
                default:
                    Log.d(TAG, "Zone is not selected");
                    callbackContext.error("INVALID_ZONEINFO");
                    return false;
                }
            }
        }
    } catch (Exception e) {

        callbackContext.error(e.getMessage());
    }

    if (action.equals("action_main")) {

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "Action is action_main");
        }
        if (!windowSupport) {
            return false;
        }

        cordova.getThreadPool().execute(new Runnable() {

            public void run() {

                Intent intent = new Intent(Intent.ACTION_MAIN);
                int packageNameIndex = 0;
                int activityNameIndex = 0;
                float scaleInfo = 0;
                int zoneInfo = getZoneInfo();
                String windowType = getWindowType();

                if (windowType.equalsIgnoreCase("splitstyle")) {
                    packageNameIndex = mainSsOptions.PACKAGE_NAME.ordinal();
                    activityNameIndex = mainSsOptions.ACTIVITY_NAME.ordinal();
                } else {
                    packageNameIndex = mainFsOptions.PACKAGE_NAME.ordinal();
                    activityNameIndex = mainFsOptions.ACTIVITY_NAME.ordinal();
                }

                try {
                    intent.setComponent(new ComponentName(args.getString(packageNameIndex),
                            args.getString(activityNameIndex)));

                    if (windowType.equalsIgnoreCase("splitstyle")) {
                        SMultiWindowActivity.makeMultiWindowIntent(intent, zoneInfo);
                    } else {

                        scaleInfo = ((float) args.getDouble(mainFsOptions.SCALE_INFO.ordinal())) / 100;
                        if (scaleInfo < 0.6 || scaleInfo > 1.0) {
                            callbackContext.error("INVALID_SCALEINFO");
                            return;
                        }
                        SMultiWindowActivity.makeMultiWindowIntent(intent, scaleInfo);
                    }
                } catch (Exception e) { // May be JSONException

                    callbackContext.error(e.getMessage());
                }
                try {
                    cordova.getActivity().startActivity(intent);
                } catch (ActivityNotFoundException activityNotFound) {
                    callbackContext.error("ACTIVITY_NOT_FOUND");
                }

                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
            }
        });
        return true;

    } else if (action.equals("action_view")) {

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "Action is action_view");
        }
        if (!windowSupport) {
            return false;
        }

        cordova.getThreadPool().execute(new Runnable() {

            public void run() {

                int dataUriIndex = 0;
                float scaleInfo = 0;
                Intent dataUrl = null;
                String windowType = getWindowType();
                int zoneInfo = getZoneInfo();

                if (windowType.equalsIgnoreCase("splitstyle")) {
                    dataUriIndex = viewSsOptions.DATA_URI.ordinal();

                } else {
                    dataUriIndex = viewFsOptions.DATA_URI.ordinal();
                }
                String dataUri = null;
                try {
                    dataUri = args.getString(dataUriIndex);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (dataUri == null || dataUri.equals("") || dataUri.equals("null")) {
                    callbackContext.error("INVALID_DATA_URI");
                    return;
                } else {
                    boolean isUriProper = false;
                    for (String schema : URI_SCHEMA_SUPPORTED) {
                        if (dataUri.startsWith(schema)) {
                            isUriProper = true;
                            break;
                        }
                    }
                    if (!isUriProper) {
                        callbackContext.error("INVALID_DATA_URI");
                        return;
                    }
                }
                try {
                    dataUrl = new Intent(Intent.ACTION_VIEW, Uri.parse(dataUri));

                    if (windowType.equalsIgnoreCase("splitstyle")) {
                        SMultiWindowActivity.makeMultiWindowIntent(dataUrl, zoneInfo);
                    } else {
                        scaleInfo = ((float) args.getDouble(viewFsOptions.SCALE_INFO.ordinal())) / 100;
                        if (scaleInfo < 0.6 || scaleInfo > 1.0) {
                            callbackContext.error("INVALID_SCALEINFO");
                            return;
                        }
                        SMultiWindowActivity.makeMultiWindowIntent(dataUrl, scaleInfo);
                    }
                } catch (Exception e) { // May be JSONException

                    callbackContext.error(e.getMessage());
                }

                try {

                    if (dataUrl != null) {
                        cordova.getActivity().startActivity(dataUrl);
                    }

                } catch (ActivityNotFoundException activityNotFound) {
                    callbackContext.error("ACTIVITY_NOT_FOUND");
                }
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
            }
        });
        return true;

    } else if (action.equals("action_check")) {

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "Action is action_check");
        }

        if (windowSupport) {

            callbackContext.success();
        }
        return true;

    } else if (action.equals("action_getapps")) {

        if (Log.isLoggable(MULTIWINDOW, Log.DEBUG)) {
            Log.d(TAG, "Action is action_getapps");
        }

        if (!windowSupport) {

            return false;
        }

        getMultiWindowApps(windowType, callbackContext);
        return true;

    }

    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, 0));
    return false;
}

From source file:com.samsung.richnotification.RichNotification.java

License:Apache License

/**
 * This function will send a new notification or will update the notification sent.
 *
 * @param data/*from  w ww  .  j  a v a  2  s  .  c  o m*/
*            The JSONArray with parameters required for sending the notification.
 * @param callbackContext
 *            The callback id used when calling back into JavaScript.
 * @return true if the notification is sent or false if the notification is not sent.
 *
 */
private boolean sendRichNotification(JSONArray data, CallbackContext callbackContext) throws JSONException {
    RichNotificationOptions options = null;
    SrnPrimaryTemplate primaryTemplate = null;
    SrnSecondaryTemplate secondaryTemplate = null;

    // This function takes care of error callbacks
    if (!initRichNotification(callbackContext)) {
        Log.e(TAG, "Initialization failed.");
        return false;
    }

    if (Log.isLoggable(RICHNOTI, Log.DEBUG))
        Log.d(TAG, "Creating the notification.");

    // Fetch options from the data object
    options = new RichNotificationOptions(data);
    options.printLogs();

    SrnRichNotification noti = null;
    UUID uuid = null;

    try {
        uuid = UUID.fromString(options.uuid);
    } catch (IllegalArgumentException invalidUUID) {
        Log.e(TAG, "Invalid UUID supplied. Creating a new notification.");
        options.uuid = null;
    }

    if (options.uuid == null)
        noti = new SrnRichNotification(mContext);
    else
        noti = new SrnRichNotification(mContext, uuid);

    // Set notification icon
    if (!options.notificationIcon.isEmpty()) {
        Bitmap notiIconBit = RichNotificationHelper.getIconBitmap(mContext,
                "file://" + options.notificationIcon);
        SrnImageAsset notiIconAsst = new SrnImageAsset(mContext, "notiIcon", notiIconBit);
        noti.setIcon(notiIconAsst);
    }

    noti.setAlertType(options.alertType, options.popupType);

    noti.setReadout(options.readoutTitle, options.readout);
    noti.setTitle(options.notificationTitle);

    primaryTemplate = RichNotificationHelper.createPrimaryTemplate(mContext, options);
    secondaryTemplate = RichNotificationHelper.createSecondaryTemplate(mContext, options);

    noti.setPrimaryTemplate(primaryTemplate);

    if (secondaryTemplate != null)
        noti.setSecondaryTemplate(secondaryTemplate);

    // Action related
    List<SrnAction> actionList = RichNotificationHelper.createActions(mContext, callbackContext, options);
    if (actionList != null) {
        noti.addActions(actionList);
    } else {
        if (Log.isLoggable(RICHNOTI, Log.DEBUG))
            Log.d(TAG, "Actions not defined");
    }

    try {
        options.uuid = mRichNotificationManager.notify(noti).toString();

        JSONObject successMsg = new JSONObject();
        successMsg.put("returnType", RichNotificationHelper.RETURN_TYPE_NOTIFICATION_SENT);
        successMsg.put("returnValue", options.uuid);

        if (Log.isLoggable(RICHNOTI, Log.DEBUG))
            Log.d(TAG, "Notification sent. UUID: " + options.uuid);
        PluginResult sentResult = new PluginResult(PluginResult.Status.OK, successMsg);
        sentResult.setKeepCallback(true);
        callbackContext.sendPluginResult(sentResult);
        return true;
    } catch (SecurityException secEx) {
        Log.e(TAG, "Permission denied");
        callbackContext.error(RichNotificationHelper.PERMISSION_DENIED);
        return false;
    }
}

From source file:com.samsung.richnotification.RichNotification.java

License:Apache License

@Override
//On RichNotification Read in the gear
public void onRead(UUID arg0) {
    if (mCallbackContext == null)
        return;/*from w  ww  .j a va  2s.  c om*/
    try {
        JSONObject eventMsg = new JSONObject();
        eventMsg.put("returnType", RichNotificationHelper.RETURN_TYPE_NOTIFICATION_READ);
        eventMsg.put("returnValue", arg0.toString());
        PluginResult sentResult = new PluginResult(PluginResult.Status.OK, eventMsg);
        sentResult.setKeepCallback(true);
        mCallbackContext.sendPluginResult(sentResult);
    } catch (JSONException jse) {
        if (Log.isLoggable(RICHNOTI, Log.DEBUG))
            Log.d(TAG, "Gear input invalid");
        return;
    }
}

From source file:com.samsung.richnotification.RichNotification.java

License:Apache License

@Override
//On RichNotification Removed from the gear
public void onRemoved(UUID arg0) {
    if (mCallbackContext == null)
        return;/* w w  w. j  a v a  2 s.c o  m*/
    try {
        JSONObject eventMsg = new JSONObject();
        eventMsg.put("returnType", RichNotificationHelper.RETURN_TYPE_NOTIFICATION_REMOVED);
        eventMsg.put("returnValue", arg0.toString());
        PluginResult sentResult = new PluginResult(PluginResult.Status.OK, eventMsg);
        sentResult.setKeepCallback(true);
        mCallbackContext.sendPluginResult(sentResult);
    } catch (JSONException jse) {
        if (Log.isLoggable(RICHNOTI, Log.DEBUG))
            Log.d(TAG, "Gear input invalid");
        return;
    }
}

From source file:com.samsung.spen.SpenException.java

License:Apache License

/**
 * This method is used for sending the intermittent plugin results to the
 * application/*from ww  w. j a v a  2  s  .  c  o m*/
 * 
 * @param type
 *            SpenExceptionType
 * @param callbackContext
 *            Context of callback
 */
public static void sendPluginResult(SpenExceptionType type, CallbackContext callbackContext) {
    PluginResult pluginResult;
    switch (type) {

    case FAILED_RECOGNIZE_TEXT:
        pluginResult = new PluginResult(PluginResult.Status.ERROR,
                SpenException.SpenExceptionType.FAILED_RECOGNIZE_TEXT.toString());
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        break;

    case FAILED_RECOGNIZE_SHAPE:
        pluginResult = new PluginResult(PluginResult.Status.ERROR,
                SpenException.SpenExceptionType.FAILED_RECOGNIZE_SHAPE.toString());
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        break;

    case FAILED_SET_BACKGROUND_IMAGE:
        pluginResult = new PluginResult(PluginResult.Status.ERROR,
                SpenException.SpenExceptionType.FAILED_SET_BACKGROUND_IMAGE.toString());
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        break;

    case FAILED_CREATE_SURFACE:
        pluginResult = new PluginResult(PluginResult.Status.ERROR,
                SpenException.SpenExceptionType.FAILED_CREATE_SURFACE.toString());
        pluginResult.setKeepCallback(false);
        callbackContext.sendPluginResult(pluginResult);
        break;

    case SURFACE_ID_NOT_EXISTS:
        pluginResult = new PluginResult(PluginResult.Status.ERROR,
                SpenExceptionType.SURFACE_ID_NOT_EXISTS.toString());
        pluginResult.setKeepCallback(false);
        callbackContext.sendPluginResult(pluginResult);
        break;

    case FAILED_SAVING_IMAGE:
        pluginResult = new PluginResult(PluginResult.Status.ERROR,
                SpenExceptionType.FAILED_SAVING_IMAGE.toString());
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        break;

    case INLINE_SURFACE_LIMIT_REACHED:
    case POPUP_SURFACE_LIMIT_REACHED:
    case MAX_HEAP_MEMORY_REACHED:
    case INVALID_SURFACE_ID:
    case INVALID_RETURN_TYPE:
    case INVALID_SURFACE_TYPE:
    case INVALID_FLAGS:
    case INVALID_INLINE_CORDINATES:
    case INVALID_DIMENSIONS:
    case MAX_SURFACE_LIMIT_REACHED:
    case SURFACE_ID_ALREADY_EXISTS:
        callbackContext.error(type.toString());
        break;
    default:
        break;
    }
}

From source file:com.samsung.spen.SPenInlineSurface.java

License:Apache License

/**
 * create SPen surface/* www.  j  a  va2s. c  om*/
 */
boolean createSPenSurface() {
    if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
        Log.d(TAG, "Inside createSPenSurface, creating SpenSurface");
    }
    Activity activity = mContextParams.getSpenCustomDrawPlugin().cordova.getActivity();
    boolean isSurface = false;
    SurfacePosition surfacePosition = mOptions.getSurfacePosition();

    mRelativeLayout.setBackgroundColor(mOptions.getColor());
    // Adding top traybar
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    int resId = activity.getResources().getIdentifier("spentraybar_top", "layout", activity.getPackageName());
    RelativeLayout traybar_top = (RelativeLayout) View.inflate(activity, resId, null);
    lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    mRelativeLayout.addView(traybar_top, lp);

    Spen spenPackage = new Spen();

    boolean isStatic = false;
    resId = activity.getResources().getIdentifier("spen_static", "bool", activity.getPackageName());
    try {
        if (resId != 0) {
            isStatic = activity.getResources().getBoolean(resId);
        }
    } catch (Resources.NotFoundException re) {
        isStatic = false;
    }

    try {
        if (isStatic) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Initializing spen Statically");
            }
            spenPackage.initialize(activity.getApplicationContext(), 5, Spen.SPEN_STATIC_LIB_MODE);
        } else {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Initializing spen Dynamically");
            }
            spenPackage.initialize(activity.getApplicationContext());
        }

        mSpenSurfaceView = new SpenSurfaceView(activity.getApplicationContext());

        // create layout for the surface
        lp = new RelativeLayout.LayoutParams(surfacePosition.getWidth(), surfacePosition.getHeight());
        lp.addRule(RelativeLayout.BELOW, traybar_top.getId());
        ViewGroup viewGroup = (ViewGroup) mContextParams.getSpenCustomDrawPlugin().webView;
        if (viewGroup != null) {
            spenSurfaceViewContainer = new RelativeLayout(activity);
            spenSurfaceViewContainer.addView(mSpenSurfaceView);
            mRelativeLayout.addView(spenSurfaceViewContainer, lp);

            // Adding Basic colors
            resId = activity.getResources().getIdentifier("spentraybar_basic_colors", "layout",
                    activity.getPackageName());
            LinearLayout basic_colors = (LinearLayout) View.inflate(activity, resId, null);
            lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.BELOW, traybar_top.getId());
            mRelativeLayout.addView(basic_colors, lp);

            mRelativeLayout.setTranslationX(surfacePosition.getxValue());
            mRelativeLayout.setTranslationY(surfacePosition.getyValue());
            viewGroup.addView(mRelativeLayout);

            int widthValue = surfacePosition.getWidth();
            int heightValue = surfacePosition.getHeight()
                    - (int) (((float) 24) * activity.getResources().getDisplayMetrics().density);
            mSpenNoteDoc = new SpenNoteDoc(activity.getApplicationContext(), widthValue, heightValue);
            mSpenPageDoc = mSpenNoteDoc.appendPage();
            mSpenPageDoc.setBackgroundColor(mOptions.getColor());
            mSpenPageDoc.clearHistory();
            mSpenSurfaceView.setPageDoc(mSpenPageDoc, true);

            // set Pen Setting info
            mPenInfo = new SpenSettingPenInfo();
            mPenInfo.size = PEN_SIZE;
            mPenInfo.color = Color.BLUE;
            mPenInfo.name = PEN_TYPE;
            Log.d(TAG, "mPenInfo:" + mPenInfo.name);
            mSpenSurfaceView.setPenSettingInfo(mPenInfo);
            setBgImage(mOptions);
            isSurface = true;
        }
    } catch (SsdkUnsupportedException e) {
        Log.d(TAG, "failed initializing the spen package " + e.getMessage());
        e.printStackTrace();
        PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getType());
        pluginResult.setKeepCallback(false);
        mContextParams.getCallbackContext().sendPluginResult(pluginResult);
        closeSurfaceControls();
    } catch (IOException e) {
        Log.d(TAG, "cannot create new doc: " + e.getMessage());
        e.printStackTrace();
        SpenException.sendPluginResult(SpenExceptionType.FAILED_CREATE_SURFACE,
                mContextParams.getCallbackContext());
        closeSurfaceControls();
    } catch (OutOfMemoryError e) {
        Runtime runtime = Runtime.getRuntime();
        Log.d(TAG, "Memory Usage, Memory Used: " + runtime.totalMemory() + " , Max Memory: "
                + runtime.maxMemory());
        e.printStackTrace();
        closeSurfaceControls();
        SpenException.sendPluginResult(SpenExceptionType.MAX_HEAP_MEMORY_REACHED,
                mContextParams.getCallbackContext());
    }
    return isSurface;
}

From source file:com.samsung.spen.SpenPlugin.java

License:Apache License

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
        Log.d(TAG, "Inside execute");
    }/*from  ww w.j av  a 2  s .  c o  m*/

    // sometimes, init is not called from initialize
    init();
    // Do not allow apis if metadata is missing
    if (!pluginMetadata) {
        callbackContext.error("METADATA_MISSING");
        Log.e(TAG, "Metadata is missing");
        return false;
    }

    initContextDetails(callbackContext);
    final CallbackContext finalCallbackContext = callbackContext;
    mSpenState = isSpenFeatureEnabled(mActivity.getApplicationContext(), callbackContext);
    if (action.equals("isSupported")) {
        if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
            Log.d(TAG, "Inside isSpenSupported");
        }
        if (mSpenState == SPEN_AND_HAND_SUPPORTED) {
            callbackContext.success(SpenExceptionType.SPEN_AND_HAND_SUPPORTED.toString());
            return true;
        } else if (mSpenState == ONLY_HAND_SUPPORTED) {
            callbackContext.success(SpenExceptionType.ONLY_HAND_SUPPORTED.toString());
            // handled this in isSpenFeatureEnabled itself as it common
            // for many cases.
        }
    } else if (action.equals("launchSurfaceInline")) {
        if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
            Log.d(TAG, "creating the spen surface inline");
        }
        SpenTrayBarOptions options = createTrayBarOptions(args, Utils.SURFACE_INLINE, callbackContext);
        final SpenTrayBarOptions inlineOptions = options;
        if (inlineOptions != null && mSpenState != SPEN_INITILIZATION_ERROR) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String id = inlineOptions.getId();
                    if (mSpenSurfaceViews.getSurfaceView(id) == null) {
                        if (surfaceCount >= SpenSurfaceViews.MAX_SURFACE_COUNT) {
                            SpenException.sendPluginResult(SpenExceptionType.MAX_SURFACE_LIMIT_REACHED,
                                    finalCallbackContext);
                        } else {
                            SPenSurfaceWithTrayBar mPaintViewTrayBar = null;
                            mPaintViewTrayBar = new SPenSurfaceWithTrayBar(mContextParams, inlineOptions);
                            mSpenSurfaceViews.addSurfaceView(id, mPaintViewTrayBar);
                            surfaceCount++;
                            if (!mSpenSurfaceViews.getSurfaceView(id).createSPenSurfaceWithTrayBar()) {
                                mSpenSurfaceViews.removeSurfaceView(id);
                                surfaceCount--;
                                SpenException.sendPluginResult(SpenExceptionType.FAILED_CREATE_SURFACE,
                                        finalCallbackContext);
                            } else {
                                // finalCallbackContext.success();
                                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "");
                                pluginResult.setKeepCallback(true);
                                finalCallbackContext.sendPluginResult(pluginResult);
                            }
                        }
                    } else {
                        SpenException.sendPluginResult(SpenExceptionType.SURFACE_ID_ALREADY_EXISTS,
                                finalCallbackContext);
                    }
                }
            });
        }
    } else if (action.equals("launchSurfacePopup")) {
        if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
            Log.d(TAG, "creating the spen surface popup");
        }
        SpenTrayBarOptions options = createTrayBarOptions(args, Utils.SURFACE_POPUP, callbackContext);
        if (options != null && mSpenState != SPEN_INITILIZATION_ERROR) {
            String id = options.getId();
            if (mSpenSurfaceViewsPopup.getSurfaceView(id) == null) {
                if (surfaceCount >= SpenSurfaceViews.MAX_SURFACE_COUNT) {
                    SpenException.sendPluginResult(SpenExceptionType.MAX_SURFACE_LIMIT_REACHED,
                            finalCallbackContext);
                } else {
                    SPenSurfaceWithTrayBar mPaintViewTrayBar = null;
                    mPaintViewTrayBar = new SPenSurfaceWithTrayBar(mContextParams, options);
                    mSpenSurfaceViewsPopup.addSurfaceView(id, mPaintViewTrayBar);
                    surfaceCount++;
                    if (!mSpenSurfaceViewsPopup.getSurfaceView(id).createSPenSurfaceWithTrayBar()) {
                        mSpenSurfaceViewsPopup.removeSurfaceView(id);
                        surfaceCount--;
                        SpenException.sendPluginResult(SpenExceptionType.FAILED_CREATE_SURFACE,
                                finalCallbackContext);
                    } else {
                        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "");
                        pluginResult.setKeepCallback(true);
                        finalCallbackContext.sendPluginResult(pluginResult);
                    }
                }
            } else {
                mSpenSurfaceViewsPopup.getSurfaceView(id).changeSPenTrayBarOptions(options, mContextParams);
                mSpenSurfaceViewsPopup.getSurfaceView(id).openSPenSurfaceWithTrayBar();
            }
        }
    } else if (action.equals("removeSurfaceInline")) {
        if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
            Log.d(TAG, "removing SpenSurface Inline");
        }

        String tempId = args.getString(ID);
        if (tempId != null) {
            tempId = tempId.trim();
            if (tempId.length() > MAX_ID_LENGTH) {
                tempId = tempId.substring(0, MAX_ID_LENGTH);
            }
        }

        final String id = tempId;
        if (id == null || id.equals("") || id.equals("null")) {
            SpenException.sendPluginResult(SpenExceptionType.INVALID_SURFACE_ID, callbackContext);
            return false;
        }

        if (mSpenState != SPEN_INITILIZATION_ERROR) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mSpenSurfaceViews.getSurfaceView(id) != null) {
                        surfaceCount--;
                        mSpenSurfaceViews.getSurfaceView(id).removeSurface();
                        mSpenSurfaceViews.removeSurfaceView(id);
                        finalCallbackContext.success(id);
                    } else {
                        SpenException.sendPluginResult(SpenExceptionType.SURFACE_ID_NOT_EXISTS,
                                finalCallbackContext);
                    }
                }
            });
        }
    } else if (action.equals("removeSurfacePopup")) {
        if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
            Log.d(TAG, "removing SpenSurface Popup");
        }
        String tempId = args.getString(ID);
        if (tempId != null) {
            tempId = tempId.trim();
            if (tempId.length() > MAX_ID_LENGTH) {
                tempId = tempId.substring(0, MAX_ID_LENGTH);
            }
        }

        final String id = tempId;

        if (id == null || id.equals("") || id.equals("null")) {
            SpenException.sendPluginResult(SpenExceptionType.INVALID_SURFACE_ID, callbackContext);
            return false;
        }

        if (mSpenSurfaceViewsPopup.getSurfaceView(id) != null) {
            surfaceCount--;
            mSpenSurfaceViewsPopup.getSurfaceView(id).removeSurface();
            mSpenSurfaceViewsPopup.removeSurfaceView(id);
            finalCallbackContext.success(id);
        } else {
            SpenException.sendPluginResult(SpenExceptionType.SURFACE_ID_NOT_EXISTS, finalCallbackContext);
        }
    } else {
        callbackContext.error(SpenExceptionType.ACTION_INVALID.toString());
        return false;
    }
    return true;
}

From source file:com.samsung.spen.SpenPlugin.java

License:Apache License

/**
 * checks if the Spen feature is enabled or not. Send the result as
 * SPEN_SUPPORTED if the Spen is supported otherwise the corresponding error
 * message./*from w w w.  j  ava 2  s  .  c o  m*/
 * 
 * @param context
 *                Context
 * @param callbackContext
 *                CallbackContext
 * @return spenState
 */
private int isSpenFeatureEnabled(Context context, CallbackContext callbackContext) {
    if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
        Log.d(TAG, "inside isSpenFeatureEnabled");
    }
    int spenState = SPEN_INITILIZATION_ERROR;
    Spen spenPackage = new Spen();
    try {
        if (isStatic) {
            spenPackage.initialize(context, 5, Spen.SPEN_STATIC_LIB_MODE);
        } else {
            spenPackage.initialize(context);
        }
        if (spenPackage.isFeatureEnabled(Spen.DEVICE_PEN)) {
            spenState = SPEN_AND_HAND_SUPPORTED;
        } else {
            spenState = ONLY_HAND_SUPPORTED;
        }
    } catch (SsdkUnsupportedException e) {
        Log.d(TAG, "failed initializing the spen package " + e.getMessage());
        e.printStackTrace();
        // if the spen sdk version name (dynamic sdk) is lesser than
        // the jar version name (which is inlcuded in the spen plugin
        // then LIBRARY_UPDATE_IS_REQUIRED should be thrown.
        // Current, Spen SDK not handled it properly.
        SpenExceptionType errorType = null;
        boolean isExceptionTypeFound = false;
        if (spenPackage != null && !isStatic) {
            String dynamicSDKPkgName = Spen.SPEN_NATIVE_PACKAGE_NAME;
            try {
                PackageInfo packageInfo = mActivity.getPackageManager().getPackageInfo(dynamicSDKPkgName, 0);
                if (packageInfo != null) {
                    String dynamicSDKVersionName = packageInfo.versionName.replace(".", "");
                    String pluginJarVersionName = spenPackage.getVersionName().replace(".", "");
                    if (dynamicSDKVersionName.compareTo(pluginJarVersionName) < 0) {
                        errorType = SpenExceptionType.LIBRARY_UPDATE_IS_REQUIRED;
                        isExceptionTypeFound = true;
                    }
                }
            } catch (NameNotFoundException e1) {
                e1.printStackTrace();
            }
        }
        if (!isExceptionTypeFound) {
            errorType = SpenException.processUnsupportedException(e);
        }
        PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, errorType.toString());
        pluginResult.setKeepCallback(false);
        callbackContext.sendPluginResult(pluginResult);
    }
    spenPackage = null;
    return spenState;
}

From source file:com.samsung.spen.SPenPopupSurface.java

License:Apache License

/**
 * create SPen surface/*from   www.  java2s . c  om*/
 * 
 * @return true if surface created otherwise false
 */
boolean createSPenSurface() {
    Activity activity = mContextParams.getSpenCustomDrawPlugin().cordova.getActivity();
    boolean isSurface = true;
    if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
        Log.d(TAG, "Inside createSPenSurface");
    }
    if (mDialog == null) {
        mDialog = new Dialog(activity);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        mDialog.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                if (mSpenSettingPenLayout != null) {
                    mSpenSettingPenLayout.setVisibility(View.GONE);
                }
                if (mSelectionSettingView != null) {
                    mSelectionSettingView.setVisibility(View.GONE);
                }
                mSpenSurfaceView.closeControl();
            }
        });
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
            Log.d(TAG, "Dialog was null, creating new dialog. Dialog:" + mDialog.toString());
        }
    }

    mRelativeLayout.setBackgroundColor(mOptions.getColor());
    // Adding top traybar buttons
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);

    int resId = activity.getResources().getIdentifier("spentraybar_top", "layout", activity.getPackageName());
    RelativeLayout traybar_top = (RelativeLayout) View.inflate(activity, resId, null);
    lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    mRelativeLayout.addView(traybar_top, lp);

    // Adding bottom traybar
    RelativeLayout traybar_bottom = null;
    if ((mOptions.getsPenFlags() & Utils.FLAG_ADD_PAGE) == Utils.FLAG_ADD_PAGE) {
        resId = activity.getResources().getIdentifier("spentraybar_bottom", "layout",
                activity.getPackageName());
        traybar_bottom = (RelativeLayout) View.inflate(activity, resId, null);
        lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        mRelativeLayout.addView(traybar_bottom, lp);
    }

    final Point point = getWidthAndHeightForPageDoc();
    mPageDocSizes = point;

    try {
        Spen spenPackage = new Spen();
        boolean isStatic = false;
        resId = activity.getResources().getIdentifier("spen_static", "bool", activity.getPackageName());
        try {
            if (resId != 0) {
                isStatic = activity.getResources().getBoolean(resId);
            }
        } catch (Resources.NotFoundException re) {
            isStatic = false;
        }

        if (isStatic) {
            spenPackage.initialize(activity.getApplicationContext(), 5, Spen.SPEN_STATIC_LIB_MODE);
        } else {
            spenPackage.initialize(activity.getApplicationContext());
        }

        mSpenSurfaceView = new SpenSurfaceView(activity.getApplicationContext());
        lp = new RelativeLayout.LayoutParams(point.x, point.y);
        lp.addRule(RelativeLayout.BELOW, traybar_top.getId());

        if (traybar_bottom != null) {
            lp.addRule(RelativeLayout.ABOVE, traybar_bottom.getId());
        }

        spenSurfaceViewContainer = new RelativeLayout(activity);
        spenSurfaceViewContainer.addView(mSpenSurfaceView);
        mRelativeLayout.addView(spenSurfaceViewContainer, lp);
        int xValue = point.x;
        int yValue = point.y - (int) (((float) 24) * activity.getResources().getDisplayMetrics().density);
        mSpenNoteDoc = new SpenNoteDoc(activity.getApplicationContext(), xValue, yValue);
        mSpenPageDoc = mSpenNoteDoc.appendPage();
        mCurrentPageindex = mSpenNoteDoc.getPageIndexById(mSpenPageDoc.getId());
        mSpenPageDoc.setBackgroundColor(mOptions.getColor());
        mSpenPageDoc.clearHistory();
        mSpenSurfaceView.setPageDoc(mSpenPageDoc, true);

        mPenInfo = new SpenSettingPenInfo();
        mPenInfo.size = PEN_SIZE;
        mPenInfo.color = Color.BLUE;
        mPenInfo.name = PEN_TYPE;
        if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
            Log.d(TAG, "popup mPenInfo:" + mPenInfo.name);
        }
        mSpenSurfaceView.setPenSettingInfo(mPenInfo);

        LayoutParams p = new LayoutParams(point.x, point.y);

        // Adding Basic colors
        resId = activity.getResources().getIdentifier("spentraybar_basic_colors", "layout",
                activity.getPackageName());
        LinearLayout basic_colors = (LinearLayout) View.inflate(activity, resId, null);
        lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.BELOW, traybar_top.getId());
        mRelativeLayout.addView(basic_colors, lp);

        mDialog.setContentView(mRelativeLayout, p);
        setBgImage(mOptions);
        mDialog.show();
    } catch (SsdkUnsupportedException e) {
        Log.d(TAG, "failed initializing the spen package " + e.getMessage());
        e.printStackTrace();
        PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getType());
        pluginResult.setKeepCallback(false);
        mContextParams.getCallbackContext().sendPluginResult(pluginResult);
        closeSurfaceControls();
        isSurface = false;
    } catch (IOException e) {
        Log.d(TAG, "cannot create new doc: " + e.getMessage());
        e.printStackTrace();
        SpenException.sendPluginResult(SpenExceptionType.FAILED_CREATE_SURFACE,
                mContextParams.getCallbackContext());
        closeSurfaceControls();
        isSurface = false;
    } catch (OutOfMemoryError e) {
        Runtime runtime = Runtime.getRuntime();
        Log.d(TAG, "Memory Usage, Memory Used: " + runtime.totalMemory() + " , Max Memory: "
                + runtime.maxMemory());
        e.printStackTrace();
        closeSurfaceControls();
        SpenException.sendPluginResult(SpenExceptionType.MAX_HEAP_MEMORY_REACHED,
                mContextParams.getCallbackContext());
        isSurface = false;
    }

    mOrientationListener = new OrientationEventListener(activity.getApplicationContext()) {
        int orntation = Configuration.ORIENTATION_PORTRAIT;

        @Override
        public void onOrientationChanged(int orientation) {
            Activity activity = mContextParams.getSpenCustomDrawPlugin().cordova.getActivity();
            if (orntation != activity.getResources().getConfiguration().orientation) {
                if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                    Log.d(TAG, "onOrientationChanged() called");
                }
                orntation = activity.getResources().getConfiguration().orientation;
                Message msgObj = handler.obtainMessage();
                Bundle b = new Bundle();
                b.putInt("orientation", orntation);
                msgObj.setData(b);
                handler.sendMessage(msgObj);
            }
        }
    };

    if (mOrientationListener.canDetectOrientation() == true) {
        if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
            Log.d(TAG, "Can detect orientation");
        }
        mOrientationListener.enable();
    }
    return isSurface;
}