com.codename1.impl.android.AndroidNativeUtil Java Examples

The following examples show how to use com.codename1.impl.android.AndroidNativeUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FacebookImpl.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
public static void init() {
    FacebookConnect.implClass = FacebookImpl.class;
    permissions = new ArrayList<String>();
    String permissionsStr = Display.getInstance().getProperty("facebook_permissions", "");
    permissionsStr = permissionsStr.trim();

    StringTokenizer token = new StringTokenizer(permissionsStr, ", ");
    if (token.countTokens() > 0) {
        try {
            while (token.hasMoreElements()) {
                String permission = (String) token.nextToken();
                permission = permission.trim();
                permissions.add(permission);
            }
        } catch (Exception e) {
            //the pattern is not valid
        }

    }
    FacebookSdk.sdkInitialize(AndroidNativeUtil.getContext().getApplicationContext());

}
 
Example #2
Source File: FacebookImpl.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
public void askPublishPermissions(final LoginCallback cb) {
    if (AndroidNativeUtil.getActivity() == null) {
        throw new RuntimeException("Cannot ask for publish permissions when running in the background.");
    
    }
    if (loginLock) {
        return;
    }
    loginLock = true;

    LoginManager login = LoginManager.getInstance();
    final CallbackManager mCallbackManager = CallbackManager.Factory.create();
    final CodenameOneActivity activity = (CodenameOneActivity) AndroidNativeUtil.getActivity();
    activity.setIntentResultListener(new IntentResultListener() {

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            mCallbackManager.onActivityResult(requestCode, resultCode, data);
            activity.restoreIntentResultListener();
        }
    });
    login.registerCallback(mCallbackManager, new FBCallback(cb));
    login.logInWithPublishPermissions(activity, PUBLISH_PERMISSIONS);
}
 
Example #3
Source File: ParseInstallationNativeImpl.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
public void initialize(String apiEndPoint, String applicationId, String clientKey) {
    String endPoint = apiEndPoint;
    if (endPoint != null && !endPoint.endsWith("/")) {
        endPoint += "/"; // Note: Url needs to have a trailing slash 
    }
    
    Parse.initialize(new Parse.Configuration.Builder(AndroidNativeUtil.getActivity())
        .applicationId(applicationId)
        .clientKey(clientKey)
        .server(endPoint)
        .build()
    );
}
 
Example #4
Source File: CN1AndroidApplication.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    // Parse native SDK should be initialized in the application class 
    // and not in the activity otherwise push notifications will only be received 
    // when the application is running (which is generally undesirable).
    //
    // See: http://stackoverflow.com/questions/26637730/where-to-place-the-parse-initialize
    // and https://parse.com/questions/cannot-send-push-to-android-after-app-is-closed-until-screen-unlock
    Parse.initialize(new Parse.Configuration.Builder(this)
        .applicationId("OiTzm1ivZovdmMktQnqk8ajqBVIPgl4dlgUxw4dh")
        .clientKey("fHquv9DA0SA5pd7VPO38tNzOrzrgTgfd7yY3nXbo")
        .server("https://parseapi.back4app.com")
        .build()
    );
    
    // Creates a unique installation representing the given device
    // and persists it to the Parse backend. 
    // Without an installation, a device cannot be targeted for push notifications.
    ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {

           @Override
           public void done(com.parse.ParseException error) {
                if (error == null) {
                    ParsePush.handlePushRegistrationStatus(null, 0); // success
                }  else {
                    ParsePush.handlePushRegistrationStatus(error.getMessage(), 3); // saving installation related failure
                }
            }
        }
    );
    
    // Tracks the application state so that pushes can be handled according to the 
    // state.
    initializeLifecycleListener();
    AndroidNativeUtil.addLifecycleListener(lifecycleListener);
}
 
Example #5
Source File: GoogleImpl.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
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()));
            }
        });
    }
}
 
Example #6
Source File: AndroidLocationPlayServiceManager.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void clearBackgroundListener() {
    final Class bgListenerClass = getBackgroundLocationListener();
    if (bgListenerClass == null) {
        return;
    }
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            //mGoogleApiClient must be connected
            while (!getmGoogleApiClient().isConnected()) {
                try {
                    Thread.sleep(300);
                } catch (Exception ex) {
                }
            }
            Handler mHandler = new Handler(Looper.getMainLooper());
            mHandler.post(new Runnable() {

                public void run() {
                    Context context = AndroidNativeUtil.getContext().getApplicationContext();
                    PendingIntent pendingIntent = createBackgroundPendingIntent();
                    removeLocationUpdates(context, pendingIntent);
                }
            });
        }
    });
    t.setUncaughtExceptionHandler(AndroidImplementation.exceptionHandler);
    t.start();
}
 
Example #7
Source File: AndroidLocationPlayServiceManager.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return the mGoogleApiClient
 */
private GoogleApiClient getmGoogleApiClient() {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(AndroidNativeUtil.getContext())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        if (!mGoogleApiClient.isConnected()) {
            mGoogleApiClient.connect();
        }
    }
    
    return mGoogleApiClient;
}
 
Example #8
Source File: CN1AndroidApplication.java    From parse4cn1 with Apache License 2.0 4 votes vote down vote up
@Override
public void onTerminate() {
    AndroidNativeUtil.removeLifecycleListener(lifecycleListener);
    super.onTerminate();
}
 
Example #9
Source File: NativeCallsImpl.java    From codenameone-demos with GNU General Public License v2.0 4 votes vote down vote up
public android.view.View createNativeButton(String param) {
    Activity activity = AndroidNativeUtil.getActivity();
    android.widget.Button b = new android.widget.Button(activity);
    b.setText(param);
    return b;
}
 
Example #10
Source File: GoogleImpl.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
private GoogleApiClient getClient(SuccessCallback<GoogleApiClient> onConnected) {
    if (mGoogleApiClient == null) {
        Context ctx = AndroidNativeUtil.getContext();
        if (mGoogleApiClient == null) {
            GoogleSignInOptions gso;

            if (clientId != null && clientSecret != null) {
                System.out.println("Generating GoogleSignIn for clientID="+clientId);
                List<Scope> includeScopes = new ArrayList<Scope>();
                Scope firstScope = new Scope(Scopes.PROFILE);
                if (scope != null) {
                    for (String str : Util.split(scope, " ")) {
                        if ("profile".equals(str)) {
                            //str = Scopes.PROFILE;
                            continue;
                        } else if ("email".equals(str)) {
                            str = Scopes.EMAIL;
                        } else if (Scopes.PROFILE.equals(str)) {
                            continue;
                        }
                        if (str.trim().isEmpty()) {
                            continue;
                        }
                        includeScopes.add(new Scope(str.trim()));
                    }
                }
                gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        //.requestIdToken("555462747934-iujpd5saj4pjpibo7c6r9tbjfef22rh1.apps.googleusercontent.com")
                        .requestIdToken(clientId)
                        .requestScopes(firstScope, includeScopes.toArray(new Scope[includeScopes.size()]))
                        //.requestScopes(Plus.SCOPE_PLUS_PROFILE)
                        //.requestServerAuthCode("555462747934-iujpd5saj4pjpibo7c6r9tbjfef22rh1.apps.googleusercontent.com")
                        .requestServerAuthCode(clientId)
                        .build();
            } else {
                System.out.println("Generating GoogleSignIn without ID token");
                gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build();
            }
            mGoogleApiClient = new GoogleApiClient.Builder(ctx)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                    .build();
        }
    }
    if (mGoogleApiClient.isConnected()) {
        if (onConnected != null) {
            onConnected.onSucess(mGoogleApiClient);
        }
    } else {
        synchronized(onConnectedCallbacks) {
            if (onConnected != null) {
                onConnectedCallbacks.add(onConnected);
            }
            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect(GoogleApiClient.SIGN_IN_MODE_OPTIONAL);
            }
        }
    }
    return mGoogleApiClient;
}
 
Example #11
Source File: FacebookImpl.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
@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);
        }
    }

}
 
Example #12
Source File: AndroidLocationPlayServiceManager.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void bindListener() {
    final Class bgListenerClass = getBackgroundLocationListener();
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            //wait until the client is connected, otherwise the call to
            //requestLocationUpdates will fail
            while (!getmGoogleApiClient().isConnected()) {
                try {
                    Thread.sleep(300);
                } catch (Exception ex) {
                }
            }
            Handler mHandler = new Handler(Looper.getMainLooper());
            mHandler.post(new Runnable() {

                public void run() {
                    LocationRequest r = locationRequest;

                    com.codename1.location.LocationRequest request = getRequest();
                    if (request != null) {
                        LocationRequest lr = LocationRequest.create();
                        if (request.getPriority() == com.codename1.location.LocationRequest.PRIORITY_HIGH_ACCUARCY) {
                            lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                        } else if (request.getPriority() == com.codename1.location.LocationRequest.PRIORITY_MEDIUM_ACCUARCY) {
                            lr.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
                        } else {
                            lr.setPriority(LocationRequest.PRIORITY_LOW_POWER);
                        }
                        lr.setInterval(request.getInterval());
                        r = lr;
                    }
                    if (AndroidImplementation.getActivity() == null) {
                        // we are in the background
                        // Sometimes using regular locations in the background causes a crash
                        // so we need to use the pending intent version.
                        Context context = AndroidNativeUtil.getContext();

                        Intent intent = new Intent(context, BackgroundLocationHandler.class);
                        //there is an bug that causes this to not to workhttps://code.google.com/p/android/issues/detail?id=81812
                        //intent.putExtra("backgroundClass", getBackgroundLocationListener().getName());
                        //an ugly workaround to the putExtra bug 
                        if (bgListenerClass != null) {
                            intent.setData(Uri.parse("http://codenameone.com/a?" + bgListenerClass.getName()));
                        }
                        PendingIntent pendingIntent = PendingIntent.getService(context, 0,
                                intent,
                                PendingIntent.FLAG_UPDATE_CURRENT);
                        inMemoryBackgroundLocationListener = AndroidLocationPlayServiceManager.this;
                        

                        //LocationServices.FusedLocationApi.requestLocationUpdates(getmGoogleApiClient(), r, pendingIntent);
                        requestLocationUpdates(context, r, pendingIntent);
                    } else {
                        //LocationServices.FusedLocationApi.requestLocationUpdates(getmGoogleApiClient(), r, AndroidLocationPlayServiceManager.this);
                        requestLocationUpdates(AndroidNativeUtil.getContext(), r, AndroidLocationPlayServiceManager.this);
                    }
                }
            });
        }
    });
    t.setUncaughtExceptionHandler(AndroidImplementation.exceptionHandler);
    t.start();
}
 
Example #13
Source File: AndroidLocationPlayServiceManager.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void clearListener() {
    final Class bgListenerClass = getBackgroundLocationListener();
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            //mGoogleApiClient must be connected
            while (!getmGoogleApiClient().isConnected()) {
                try {
                    Thread.sleep(300);
                } catch (Exception ex) {
                }
            }
            Handler mHandler = new Handler(Looper.getMainLooper());
            mHandler.post(new Runnable() {

                public void run() {
                    if (inMemoryBackgroundLocationListener != null) {
                        Context context = AndroidNativeUtil.getContext();
                        Intent intent = new Intent(context, BackgroundLocationHandler.class);
                        if (bgListenerClass != null) {
                            intent.putExtra("backgroundClass", bgListenerClass.getName());
                        }
                        PendingIntent pendingIntent = PendingIntent.getService(context, 0,
                                intent,
                                PendingIntent.FLAG_UPDATE_CURRENT);

                        //LocationServices.FusedLocationApi.removeLocationUpdates(getmGoogleApiClient(), pendingIntent);
                        removeLocationUpdates(context, pendingIntent);
                        inMemoryBackgroundLocationListener = null;
                    } else {
                        //LocationServices.FusedLocationApi.removeLocationUpdates(getmGoogleApiClient(), AndroidLocationPlayServiceManager.this);
                        removeLocationUpdates(AndroidNativeUtil.getContext(), AndroidLocationPlayServiceManager.this);
                    }
                }
            });
        }
    });
    t.setUncaughtExceptionHandler(AndroidImplementation.exceptionHandler);
    t.start();
}
 
Example #14
Source File: AndroidLocationPlayServiceManager.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void bindBackgroundListener() {
    /*
    if(!AndroidNativeUtil.checkForPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION, "This is required to get the location")){
        System.out.println("Request for background location access is denied");
    }
    */

    final Class bgListenerClass = getBackgroundLocationListener();
    if (bgListenerClass == null) {
        return;
    }
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            //wait until the client is connected, otherwise the call to
            //requestLocationUpdates will fail
            while (!getmGoogleApiClient().isConnected()) {
                try {
                    Thread.sleep(300);
                } catch (Exception ex) {
                }
            }
            Handler mHandler = new Handler(Looper.getMainLooper());
            mHandler.post(new Runnable() {

                public void run() {
                    //don't be too aggressive for location updates in the background
                    LocationRequest req = LocationRequest.create();
                    setupBackgroundLocationRequest(req);
                    Context context = AndroidNativeUtil.getContext().getApplicationContext();
                    PendingIntent pendingIntent = createBackgroundPendingIntent();
                    requestLocationUpdates(context, req, pendingIntent);
                }
            });
        }
    });
    t.setUncaughtExceptionHandler(AndroidImplementation.exceptionHandler);
    t.start();
}
 
Example #15
Source File: AndroidLocationPlayServiceManager.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addGeoFencing(final Class GeofenceListenerClass, final com.codename1.location.Geofence gf) {
    //Display.getInstance().scheduleBackgroundTask(new Runnable() {
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            //wait until the client is connected, otherwise the call to
            //requestLocationUpdates will fail
            //com.codename1.io.Log.p("PLACES add "+gf.getId()+" 1");
            while (!getmGoogleApiClient().isConnected()) {
                try {
                    Thread.sleep(300);
                } catch (Exception ex) {
                }
            }
            //com.codename1.io.Log.p("PLACES add "+gf.getId()+" 2");
            Handler mHandler = new Handler(Looper.getMainLooper());
            mHandler.post(new Runnable() {

                public void run() {
                    Context context = AndroidNativeUtil.getContext();

                    Intent intent = new Intent(context, GeofenceHandler.class);
                    intent.putExtra("geofenceClass", GeofenceListenerClass.getName());
                    intent.putExtra("geofenceID", gf.getId());
                    PendingIntent pendingIntent = PendingIntent.getService(context, 0,
                            intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                    ArrayList<Geofence> geofences = new ArrayList<Geofence>();
                    geofences.add(new Geofence.Builder()
                            .setRequestId(gf.getId())
                            .setCircularRegion(gf.getLoc().getLatitude(), gf.getLoc().getLongitude(), gf.getRadius())
                            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER
                                    | Geofence.GEOFENCE_TRANSITION_EXIT)
                            .setExpirationDuration(gf.getExpiration() > 0 ? gf.getExpiration() : Geofence.NEVER_EXPIRE)
                            .build());
                    
                    LocationServices.GeofencingApi.addGeofences(getmGoogleApiClient(), geofences, pendingIntent);
                }
            });
        }
    });
    t.setUncaughtExceptionHandler(AndroidImplementation.exceptionHandler);
    t.start();
}
 
Example #16
Source File: AndroidLocationPlayServiceManager.java    From CodenameOne with GNU General Public License v2.0 4 votes vote down vote up
@Override
public boolean isGPSEnabled() {
    Context context = AndroidNativeUtil.getContext();
    android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
}