Search in sources :

Example 11 with Callback

use of com.codename1.util.Callback in project CodenameOne by codenameone.

the class AndroidImplementation method openGallery.

public void openGallery(final ActionListener response, int type) {
    if (getActivity() == null) {
        throw new RuntimeException("Cannot open galery in background mode");
    }
    if (!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to browse the photos")) {
        return;
    }
    callback = new EventDispatcher();
    callback.addListener(response);
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    if (type == Display.GALLERY_VIDEO) {
        galleryIntent.setType("video/*");
    } else if (type == Display.GALLERY_IMAGE) {
        galleryIntent.setType("image/*");
    } else if (type == -9999) {
        galleryIntent = new Intent();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            galleryIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        } else {
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        }
        galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
        // set MIME type for image
        galleryIntent.setType("*/*");
        galleryIntent.putExtra(Intent.EXTRA_MIME_TYPES, Display.getInstance().getProperty("android.openGallery.accept", "*/*").split(","));
    } else {
        galleryIntent.setType("*/*");
    }
    this.getActivity().startActivityForResult(galleryIntent, OPEN_GALLERY);
}
Also used : EventDispatcher(com.codename1.ui.util.EventDispatcher)

Example 12 with Callback

use of com.codename1.util.Callback in project CodenameOne by codenameone.

the class FacebookImpl method inviteFriends.

@Override
public void inviteFriends(String appLinkUrl, String previewImageUrl, final Callback cb) {
    if (AndroidNativeUtil.getActivity() == null) {
        throw new RuntimeException("Cannot invite friends while running in the background.");
    }
    if (AppInviteDialog.canShow()) {
        AppInviteContent content = new AppInviteContent.Builder().setApplinkUrl(appLinkUrl).setPreviewImageUrl(previewImageUrl).build();
        final CodenameOneActivity activity = (CodenameOneActivity) AndroidNativeUtil.getActivity();
        if (cb == null) {
            AppInviteDialog.show(activity, content);
        } else {
            AppInviteDialog appInviteDialog = new AppInviteDialog(activity);
            final CallbackManager mCallbackManager = CallbackManager.Factory.create();
            activity.setIntentResultListener(new IntentResultListener() {

                @Override
                public void onActivityResult(int requestCode, int resultCode, Intent data) {
                    mCallbackManager.onActivityResult(requestCode, resultCode, data);
                    activity.restoreIntentResultListener();
                }
            });
            appInviteDialog.registerCallback(mCallbackManager, new FacebookCallback<AppInviteDialog.Result>() {

                @Override
                public void onSuccess(AppInviteDialog.Result result) {
                    Display.getInstance().callSerially(new Runnable() {

                        @Override
                        public void run() {
                            cb.onSucess(null);
                        }
                    });
                }

                @Override
                public void onCancel() {
                    Display.getInstance().callSerially(new Runnable() {

                        @Override
                        public void run() {
                            cb.onError(null, null, -1, "User Cancelled");
                        }
                    });
                }

                @Override
                public void onError(final FacebookException e) {
                    Display.getInstance().callSerially(new Runnable() {

                        @Override
                        public void run() {
                            cb.onError(null, e, 0, e.getMessage());
                        }
                    });
                }
            });
            appInviteDialog.show(content);
        }
    }
}
Also used : CodenameOneActivity(com.codename1.impl.android.CodenameOneActivity) Intent(android.content.Intent) CallbackManager(com.facebook.CallbackManager) AppInviteDialog(com.facebook.share.widget.AppInviteDialog) IntentResultListener(com.codename1.impl.android.IntentResultListener) FacebookException(com.facebook.FacebookException) AppInviteContent(com.facebook.share.model.AppInviteContent)

Example 13 with Callback

use of com.codename1.util.Callback in project CodenameOne by codenameone.

the class GoogleImpl method nativeLoginImpl.

private void nativeLoginImpl(final GoogleApiClient client) {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(client);
    AndroidNativeUtil.startActivityForResult(signInIntent, RC_SIGN_IN, new IntentResultListener() {

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
            if (requestCode == RC_SIGN_IN) {
                final GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                if (result.isSuccess()) {
                    // Signed in successfully, show authenticated UI.
                    GoogleSignInAccount acct = result.getSignInAccount();
                    String displayName = acct.getDisplayName();
                    String acctId = acct.getId();
                    String email = acct.getEmail();
                    String requestIdToken = acct.getIdToken();
                    Set<Scope> grantedScopes = acct.getGrantedScopes();
                    String code = acct.getServerAuthCode();
                    String scopeStr = scope;
                    System.out.println("Token is " + acct.getIdToken());
                    if (acct.getIdToken() == null && clientId != null && clientSecret != null) {
                        Log.p("Received null ID token even though clientId and clientSecret are set.");
                    }
                    // otherwise we'll set the token to null.
                    if (clientId != null && clientSecret != null && requestIdToken != null && code != null) {
                        ConnectionRequest req = new ConnectionRequest() {

                            @Override
                            protected void readResponse(InputStream input) throws IOException {
                                Map<String, Object> json = new JSONParser().parseJSON(new InputStreamReader(input, "UTF-8"));
                                if (json.containsKey("access_token")) {
                                    setAccessToken(new AccessToken((String) json.get("access_token"), null));
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                } else {
                                    setAccessToken(new AccessToken(null, null));
                                    Log.p("Failed to retrieve the access token from the google auth server.  Login succeeded, but access token is null, so you won't be able to use it to retrieve additional information.");
                                    Log.p("Response was " + json);
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                }
                            }
                        };
                        req.setUrl("https://www.googleapis.com/oauth2/v4/token");
                        req.addArgument("grant_type", "authorization_code");
                        // req.addArgument("client_id", "555462747934-iujpd5saj4pjpibo7c6r9tbjfef22rh1.apps.googleusercontent.com");
                        req.addArgument("client_id", clientId);
                        // req.addArgument("client_secret", "650YqplrnAI0KXb9LMUnVNnx");
                        req.addArgument("client_secret", clientSecret);
                        req.addArgument("redirect_uri", "");
                        req.addArgument("code", code);
                        req.addArgument("id_token", requestIdToken);
                        req.setPost(true);
                        req.setReadResponseForErrors(true);
                        NetworkManager.getInstance().addToQueue(req);
                    } else {
                        setAccessToken(new AccessToken(null, null));
                        Log.p("The access token was set to null because one of clientId, clientSecret, requestIdToken, or auth were null");
                        Log.p("The login succeeded, but you won't be able to make any requests to Google's REST apis using the login token.");
                        Log.p("In order to obtain a token that can be used with Google's REST APIs, you need to set the clientId, and clientSecret of" + "the GoogleConnect instance to valid OAuth2.0 Client IDs for Web Clients.");
                        Log.p("See https://console.developers.google.com/apis/credentials");
                        Log.p("You can get the OAuth2.0 client ID for this project in your google-services.json file in the oauth_client section");
                        Display.getInstance().callSerially(new Runnable() {

                            @Override
                            public void run() {
                                callback.loginSuccessful();
                            }
                        });
                    }
                } else {
                    if (callback != null) {
                        if (callback != null) {
                            Display.getInstance().callSerially(new Runnable() {

                                @Override
                                public void run() {
                                    callback.loginFailed(GooglePlayServicesUtil.getErrorString(result.getStatus().getStatusCode()));
                                }
                            });
                        }
                    }
                }
            }
        }
    });
}
Also used : Set(java.util.Set) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Intent(android.content.Intent) IOException(java.io.IOException) GoogleSignInResult(com.google.android.gms.auth.api.signin.GoogleSignInResult) ConnectionRequest(com.codename1.io.ConnectionRequest) GoogleSignInAccount(com.google.android.gms.auth.api.signin.GoogleSignInAccount) IntentResultListener(com.codename1.impl.android.IntentResultListener) AccessToken(com.codename1.io.AccessToken) JSONParser(com.codename1.io.JSONParser) Map(java.util.Map)

Example 14 with Callback

use of com.codename1.util.Callback in project CodenameOne by codenameone.

the class GoogleImpl method onConnectionFailed.

public void onConnectionFailed(final ConnectionResult cr) {
    if (AndroidNativeUtil.getActivity() == null) {
        return;
    }
    final CodenameOneActivity main = (CodenameOneActivity) AndroidNativeUtil.getActivity();
    if (!mIntentInProgress && cr.hasResolution()) {
        try {
            mIntentInProgress = true;
            main.startIntentSenderForResult(cr.getResolution().getIntentSender(), 0, null, 0, 0, 0);
            main.setIntentResultListener(new com.codename1.impl.android.IntentResultListener() {

                public void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
                    mIntentInProgress = false;
                    if (!mGoogleApiClient.isConnecting()) {
                        mGoogleApiClient.connect();
                    }
                    main.restoreIntentResultListener();
                }
            });
        } catch (SendIntentException e) {
            // The intent was canceled before it was sent.  Return to the default
            // state and attempt to connect to get an updated ConnectionResult.
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
        return;
    }
    if (callback != null) {
        Display.getInstance().callSerially(new Runnable() {

            @Override
            public void run() {
                callback.loginFailed(GooglePlayServicesUtil.getErrorString(cr.getErrorCode()));
            }
        });
    }
}
Also used : IntentResultListener(com.codename1.impl.android.IntentResultListener) CodenameOneActivity(com.codename1.impl.android.CodenameOneActivity) Intent(android.content.Intent) SendIntentException(android.content.IntentSender.SendIntentException)

Example 15 with Callback

use of com.codename1.util.Callback in project CodenameOne by codenameone.

the class Capture method capturePhoto.

/**
 * <p>Invokes the camera and takes a photo synchronously while blocking the EDT, the sample below
 * demonstrates a simple usage and applying a mask to the result</p>
 * <script src="https://gist.github.com/codenameone/b18c37dfcc7de752e0e6.js"></script>
 * <img src="https://www.codenameone.com/img/developer-guide/graphics-image-masking.png" alt="Picture after the capture was complete and the resulted image was rounded. The background was set to red so the rounding effect will be more noticeable" />
 *
 * @param width the target width for the image if possible, some platforms don't support scaling. To maintain aspect ratio set to -1
 * @param height the target height for the image if possible, some platforms don't support scaling. To maintain aspect ratio set to -1
 * @return the photo file location or null if the user canceled
 */
public static String capturePhoto(int width, int height) {
    CallBack c = new CallBack();
    if ("ios".equals(Display.getInstance().getPlatformName()) && (width != -1 || height != -1)) {
        // workaround for threading issues in iOS https://github.com/codenameone/CodenameOne/issues/2246
        capturePhoto(c);
        Display.getInstance().invokeAndBlock(c);
        if (c.url == null) {
            return null;
        }
        ImageIO scale = Display.getInstance().getImageIO();
        if (scale != null) {
            try {
                String path = c.url.substring(0, c.url.indexOf(".")) + "s" + c.url.substring(c.url.indexOf("."));
                OutputStream os = FileSystemStorage.getInstance().openOutputStream(path);
                scale.save(c.url, os, ImageIO.FORMAT_JPEG, width, height, 1);
                Util.cleanup(os);
                FileSystemStorage.getInstance().delete(c.url);
                return path;
            } catch (IOException ex) {
                Log.e(ex);
            }
        }
    } else {
        c.targetWidth = width;
        c.targetHeight = height;
        capturePhoto(c);
        Display.getInstance().invokeAndBlock(c);
    }
    return c.url;
}
Also used : OutputStream(java.io.OutputStream) IOException(java.io.IOException) ImageIO(com.codename1.ui.util.ImageIO)

Aggregations

ActionListener (com.codename1.ui.events.ActionListener)14 ActionEvent (com.codename1.ui.events.ActionEvent)12 IOException (java.io.IOException)11 ConnectionRequest (com.codename1.io.ConnectionRequest)10 EventDispatcher (com.codename1.ui.util.EventDispatcher)8 NetworkEvent (com.codename1.io.NetworkEvent)6 InputStream (java.io.InputStream)5 Intent (android.content.Intent)4 ComponentAnimation (com.codename1.ui.animations.ComponentAnimation)4 ArrayList (java.util.ArrayList)4 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)3 Uri (android.net.Uri)3 IntentResultListener (com.codename1.impl.android.IntentResultListener)3 AccessToken (com.codename1.io.AccessToken)3 GZConnectionRequest (com.codename1.io.gzip.GZConnectionRequest)3 EncodedImage (com.codename1.ui.EncodedImage)3 Image (com.codename1.ui.Image)3 File (java.io.File)3 OutputStream (java.io.OutputStream)3 RandomAccessFile (java.io.RandomAccessFile)3