Search in sources :

Example 41 with PluginResult

use of org.apache.cordova.PluginResult in project jpHolo by teusink.

the class InAppBrowser method execute.

/**
     * 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) throws JSONException {
    if (action.equals("open")) {
        this.callbackContext = callbackContext;
        final String url = args.getString(0);
        String t = args.optString(1);
        if (t == null || t.equals("") || t.equals(NULL)) {
            t = SELF;
        }
        final String target = t;
        final HashMap<String, Boolean> features = parseFeature(args.optString(2));
        Log.d(LOG_TAG, "target = " + target);
        this.cordova.getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                String result = "";
                // SELF
                if (SELF.equals(target)) {
                    Log.d(LOG_TAG, "in self");
                    // load in webview
                    if (url.startsWith("file://") || url.startsWith("javascript:") || Config.isUrlWhiteListed(url)) {
                        Log.d(LOG_TAG, "loading in webview");
                        webView.loadUrl(url);
                    } else //Load the dialer
                    if (url.startsWith(WebView.SCHEME_TEL)) {
                        try {
                            Log.d(LOG_TAG, "loading in dialer");
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse(url));
                            cordova.getActivity().startActivity(intent);
                        } catch (android.content.ActivityNotFoundException e) {
                            LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
                        }
                    } else // load in InAppBrowser
                    {
                        Log.d(LOG_TAG, "loading in InAppBrowser");
                        result = showWebPage(url, features);
                    }
                } else // SYSTEM
                if (SYSTEM.equals(target)) {
                    Log.d(LOG_TAG, "in system");
                    result = openExternal(url);
                } else // BLANK - or anything else
                {
                    Log.d(LOG_TAG, "in blank");
                    result = showWebPage(url, features);
                }
                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        });
    } else if (action.equals("close")) {
        closeDialog();
    } else if (action.equals("injectScriptCode")) {
        String jsWrapper = null;
        if (args.getBoolean(1)) {
            jsWrapper = String.format("prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')", callbackContext.getCallbackId());
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectScriptFile")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectStyleCode")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectStyleFile")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("show")) {
        this.cordova.getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                dialog.show();
            }
        });
        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
        pluginResult.setKeepCallback(true);
        this.callbackContext.sendPluginResult(pluginResult);
    } else {
        return false;
    }
    return true;
}
Also used : PluginResult(org.apache.cordova.PluginResult) Intent(android.content.Intent)

Example 42 with PluginResult

use of org.apache.cordova.PluginResult in project jpHolo by teusink.

the class AudioHandler method execute.

/**
     * Executes the request and returns PluginResult.
     * @param action 		The action to execute.
     * @param args 			JSONArry of arguments for the plugin.
     * @param callbackContext		The callback context used when calling back into JavaScript.
     * @return 				A PluginResult object with a status and message.
     */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    CordovaResourceApi resourceApi = webView.getResourceApi();
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";
    if (action.equals("startRecordingAudio")) {
        String target = args.getString(1);
        String fileUriStr;
        try {
            Uri targetUri = resourceApi.remapUri(Uri.parse(target));
            fileUriStr = targetUri.toString();
        } catch (IllegalArgumentException e) {
            fileUriStr = target;
        }
        this.startRecordingAudio(args.getString(0), FileHelper.stripFileProtocol(fileUriStr));
    } else if (action.equals("stopRecordingAudio")) {
        this.stopRecordingAudio(args.getString(0));
    } else if (action.equals("startPlayingAudio")) {
        String target = args.getString(1);
        String fileUriStr;
        try {
            Uri targetUri = resourceApi.remapUri(Uri.parse(target));
            fileUriStr = targetUri.toString();
        } catch (IllegalArgumentException e) {
            fileUriStr = target;
        }
        this.startPlayingAudio(args.getString(0), FileHelper.stripFileProtocol(fileUriStr));
    } else if (action.equals("seekToAudio")) {
        this.seekToAudio(args.getString(0), args.getInt(1));
    } else if (action.equals("pausePlayingAudio")) {
        this.pausePlayingAudio(args.getString(0));
    } else if (action.equals("stopPlayingAudio")) {
        this.stopPlayingAudio(args.getString(0));
    } else if (action.equals("setVolume")) {
        try {
            this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));
        } catch (NumberFormatException nfe) {
        //no-op
        }
    } else if (action.equals("getCurrentPositionAudio")) {
        float f = this.getCurrentPositionAudio(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("getDurationAudio")) {
        float f = this.getDurationAudio(args.getString(0), args.getString(1));
        callbackContext.sendPluginResult(new PluginResult(status, f));
        return true;
    } else if (action.equals("create")) {
        String id = args.getString(0);
        String src = FileHelper.stripFileProtocol(args.getString(1));
        AudioPlayer audio = new AudioPlayer(this, id, src);
        this.players.put(id, audio);
    } else if (action.equals("release")) {
        boolean b = this.release(args.getString(0));
        callbackContext.sendPluginResult(new PluginResult(status, b));
        return true;
    } else {
        // Unrecognized action.
        return false;
    }
    callbackContext.sendPluginResult(new PluginResult(status, result));
    return true;
}
Also used : PluginResult(org.apache.cordova.PluginResult) CordovaResourceApi(org.apache.cordova.CordovaResourceApi) Uri(android.net.Uri)

Example 43 with PluginResult

use of org.apache.cordova.PluginResult in project jpHolo by teusink.

the class Capture method onActivityResult.

/**
     * Called when the video view exits.
     *
     * @param requestCode       The request code originally supplied to startActivityForResult(),
     *                          allowing you to identify who this result came from.
     * @param resultCode        The integer result code returned by the child activity through its setResult().
     * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     * @throws JSONException
     */
public void onActivityResult(int requestCode, int resultCode, final Intent intent) {
    // Result received okay
    if (resultCode == Activity.RESULT_OK) {
        // An audio clip was requested
        if (requestCode == CAPTURE_AUDIO) {
            final Capture that = this;
            Runnable captureAudio = new Runnable() {

                @Override
                public void run() {
                    // Get the uri of the audio clip
                    Uri data = intent.getData();
                    // create a file object from the uri
                    results.put(createMediaFile(data));
                    if (results.length() >= limit) {
                        // Send Uri back to JavaScript for listening to audio
                        that.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
                    } else {
                        // still need to capture more audio clips
                        captureAudio();
                    }
                }
            };
            this.cordova.getThreadPool().execute(captureAudio);
        } else if (requestCode == CAPTURE_IMAGE) {
            // For some reason if I try to do:
            // Uri data = intent.getData();
            // It crashes in the emulator and on my phone with a null pointer exception
            // To work around it I had to grab the code from CameraLauncher.java
            final Capture that = this;
            Runnable captureImage = new Runnable() {

                @Override
                public void run() {
                    try {
                        // TODO Auto-generated method stub
                        // Create entry in media store for image
                        // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
                        ContentValues values = new ContentValues();
                        values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, IMAGE_JPEG);
                        Uri uri = null;
                        try {
                            uri = that.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                        } catch (UnsupportedOperationException e) {
                            LOG.d(LOG_TAG, "Can't write to external media storage.");
                            try {
                                uri = that.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                            } catch (UnsupportedOperationException ex) {
                                LOG.d(LOG_TAG, "Can't write to internal media storage.");
                                that.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image - no media storage found."));
                                return;
                            }
                        }
                        FileInputStream fis = new FileInputStream(getTempDirectoryPath() + "/Capture.jpg");
                        OutputStream os = that.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        byte[] buffer = new byte[4096];
                        int len;
                        while ((len = fis.read(buffer)) != -1) {
                            os.write(buffer, 0, len);
                        }
                        os.flush();
                        os.close();
                        fis.close();
                        // Add image to results
                        results.put(createMediaFile(uri));
                        checkForDuplicateImage();
                        if (results.length() >= limit) {
                            // Send Uri back to JavaScript for viewing image
                            that.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
                        } else {
                            // still need to capture more images
                            captureImage();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        that.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image."));
                    }
                }
            };
            this.cordova.getThreadPool().execute(captureImage);
        } else if (requestCode == CAPTURE_VIDEO) {
            final Capture that = this;
            Runnable captureVideo = new Runnable() {

                @Override
                public void run() {
                    Uri data = null;
                    if (intent != null) {
                        // Get the uri of the video clip
                        data = intent.getData();
                    }
                    if (data == null) {
                        File movie = new File(getTempDirectoryPath(), "Capture.avi");
                        data = Uri.fromFile(movie);
                    }
                    // create a file object from the uri
                    if (data == null) {
                        that.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Error: data is null"));
                    } else {
                        results.put(createMediaFile(data));
                        if (results.length() >= limit) {
                            // Send Uri back to JavaScript for viewing video
                            that.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
                        } else {
                            // still need to capture more video clips
                            captureVideo(duration);
                        }
                    }
                }
            };
            this.cordova.getThreadPool().execute(captureVideo);
        }
    } else // If canceled
    if (resultCode == Activity.RESULT_CANCELED) {
        // If we have partial results send them back to the user
        if (results.length() > 0) {
            this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
        } else // user canceled the action
        {
            this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Canceled."));
        }
    } else // If something else
    {
        // If we have partial results send them back to the user
        if (results.length() > 0) {
            this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, results));
        } else // something bad happened
        {
            this.fail(createErrorObject(CAPTURE_NO_MEDIA_FILES, "Did not complete!"));
        }
    }
}
Also used : ContentValues(android.content.ContentValues) PluginResult(org.apache.cordova.PluginResult) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Uri(android.net.Uri) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 44 with PluginResult

use of org.apache.cordova.PluginResult in project jpHolo by teusink.

the class NetworkManager method execute.

/**
     * Executes the request and returns PluginResult.
     *
     * @param action            The action to execute.
     * @param args              JSONArry of arguments for the plugin.
     * @param callbackContext   The callback id used when calling back into JavaScript.
     * @return                  True if the action was valid, false otherwise.
     */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("getConnectionInfo")) {
        this.connectionCallbackContext = callbackContext;
        NetworkInfo info = sockMan.getActiveNetworkInfo();
        String connectionType = "";
        try {
            connectionType = this.getConnectionInfo(info).get("type").toString();
        } catch (JSONException e) {
        }
        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    }
    return false;
}
Also used : PluginResult(org.apache.cordova.PluginResult) NetworkInfo(android.net.NetworkInfo) JSONException(org.json.JSONException)

Example 45 with PluginResult

use of org.apache.cordova.PluginResult in project jpHolo by teusink.

the class Appstore method execute.

@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {

        @Override
        public void run() {
            try {
                if (action.equals("show")) {
                    final JSONObject jo = args.getJSONObject(0);
                    final String appstoreLink = jo.getString("link");
                    final String appstoreType = jo.getString("type");
                    final Intent intent = new Intent(Intent.ACTION_VIEW);
                    if (appInstalledOrNot("com.amazon.venezia") == true) {
                        if (appstoreType.equals("app")) {
                            // org.teusink.droidpapers
                            intent.setData(Uri.parse("amzn://apps/android?p=" + appstoreLink));
                        } else if (appstoreType.equals("pub")) {
                            // Teusink.org
                            intent.setData(Uri.parse("amzn://apps/android?s=" + appstoreLink));
                        }
                    } else if (appInstalledOrNot("com.android.vending") == true) {
                        if (appstoreType.equals("app")) {
                            // org.teusink.droidpapers
                            intent.setData(Uri.parse("market://details?id=" + appstoreLink));
                        } else if (appstoreType.equals("pub")) {
                            // Teusink.org
                            intent.setData(Uri.parse("market://search?q=pub:" + appstoreLink));
                        }
                    } else {
                        if (appstoreType.equals("app")) {
                            // org.teusink.droidpapers
                            // intent.setData(Uri.parse("https://play.google.com/store/apps/details?id="
                            // + appstoreLink));
                            intent.setData(Uri.parse("http://droidpapers.teusink.org/about.php"));
                        } else if (appstoreType.equals("pub")) {
                            // Teusink.org
                            // intent.setData(Uri.parse("https://play.google.com/store/apps/developer?id="
                            // + appstoreLink));
                            intent.setData(Uri.parse("http://droidpapers.teusink.org/about.php"));
                        }
                    }
                    try {
                        cordova.getActivity().startActivityForResult(intent, 0);
                    } catch (final ActivityNotFoundException e) {
                        Log.e(LOG_PROV, LOG_NAME + "Error: " + PluginResult.Status.ERROR);
                        e.printStackTrace();
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
                    }
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
                } else if (action.equals("check")) {
                    String appstore = "unknown";
                    if (appInstalledOrNot("com.amazon.venezia")) {
                        appstore = "amazon";
                    } else if (appInstalledOrNot("com.android.vending")) {
                        appstore = "google";
                    }
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, appstore));
                } else {
                    Log.e(LOG_PROV, LOG_NAME + "Error: " + PluginResult.Status.INVALID_ACTION);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
                }
            } catch (final JSONException e) {
                Log.e(LOG_PROV, LOG_NAME + "Error: " + PluginResult.Status.JSON_EXCEPTION);
                e.printStackTrace();
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
            }
        }
    });
    return true;
}
Also used : JSONObject(org.json.JSONObject) PluginResult(org.apache.cordova.PluginResult) ActivityNotFoundException(android.content.ActivityNotFoundException) JSONException(org.json.JSONException) Intent(android.content.Intent)

Aggregations

PluginResult (org.apache.cordova.PluginResult)45 JSONException (org.json.JSONException)19 JSONObject (org.json.JSONObject)15 IOException (java.io.IOException)6 JSONArray (org.json.JSONArray)6 Uri (android.net.Uri)4 FileNotFoundException (java.io.FileNotFoundException)4 AlertDialog (android.app.AlertDialog)3 DialogInterface (android.content.DialogInterface)3 Intent (android.content.Intent)3 TextView (android.widget.TextView)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 File (java.io.File)3 OutputStream (java.io.OutputStream)3 CallbackContext (org.apache.cordova.CallbackContext)3 CordovaInterface (org.apache.cordova.CordovaInterface)3 CordovaResourceApi (org.apache.cordova.CordovaResourceApi)3 NativeToJsMessageQueue (org.apache.cordova.NativeToJsMessageQueue)3 Test (org.junit.Test)3 SharedPreferences (android.content.SharedPreferences)2