Java Code Examples for com.google.android.gms.common.api.GoogleApiClient

The following are top voted examples for showing how to use com.google.android.gms.common.api.GoogleApiClient. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: SpaceRace   File: GameHelper.java   View source code 6 votes vote down vote up
/**
 * Creates a GoogleApiClient.Builder for use with @link{#setup}. Normally,
 * you do not have to do this; use this method only if you need to make
 * nonstandard setup (e.g. adding extra scopes for other APIs) on the
 * GoogleApiClient.Builder before calling @link{#setup}.
 */
public GoogleApiClient.Builder createApiClientBuilder() {
    if (mSetupDone) {
        String error = "GameHelper: you called GameHelper.createApiClientBuilder() after "
                + "calling setup. You can only get a client builder BEFORE performing setup.";
        logError(error);
        throw new IllegalStateException(error);
    }

    GoogleApiClient.Builder builder = new GoogleApiClient.Builder(
            mActivity, this, this);

    if (0 != (mRequestedClients & CLIENT_GAMES)) {
        builder.addApi(Games.API, mGamesApiOptions);
        builder.addScope(Games.SCOPE_GAMES);
    }

    if (0 != (mRequestedClients & CLIENT_SNAPSHOT)) {
      builder.addScope(Drive.SCOPE_APPFOLDER);
      builder.addApi(Drive.API);
    }

    mGoogleApiClientBuilder = builder;
    return builder;
}
 
Example 2
Project: RxGooglePhotos   File: GoogleSignOutOnSubscribe.java   View source code 6 votes vote down vote up
private void initGoogleApiClient() {
    final GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestProfile()
            .requestScopes(new Scope(SCOPE_PICASA))
            .build();
    googleApiClient = new GoogleApiClient.Builder(activity)
            .enableAutoManage(activity,
                    connectionResult -> emitter.onError(new SignInException("Connecting", connectionResult.getErrorMessage(), connectionResult.getErrorCode())))
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(@Nullable Bundle bundle) {
                    actWhenConnected();
                }

                @Override
                public void onConnectionSuspended(int i) {

                }
            })
            .build();
}
 
Example 3
Project: react-native-android-wear-demo   File: MainActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  btnIncreaseCounter = (Button) findViewById(R.id.btnWearIncreaseCounter);
  btnIncreaseCounter.getBackground().setColorFilter(0xFF1194F7, PorterDuff.Mode.MULTIPLY);
  tvCounter = (TextView) findViewById(R.id.tvCounter);
  tvCounter.setText(Integer.toString(count));

  client = new GoogleApiClient.Builder(this).addApi(Wearable.API)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .build();

  btnIncreaseCounter.setOnClickListener(clickListener);
}
 
Example 4
Project: AstronomyTourPadova   File: GmapFragment.java   View source code 6 votes vote down vote up
private void setupGeoLocation() {
    Log.d(TAG, "setupGeoLocation()");
    
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
        .addApi(LocationServices.API)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .build();
    mGoogleApiClient.connect();
    
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10 * 60 * 1000);        // 10 minutes, in milliseconds
    mLocationRequest.setFastestInterval(60 * 1000);  // 60 second, in milliseconds
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // We wanto to center the Player on his actual position
    
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(mLocationRequest);
    builder.setAlwaysShow(true); // "This app wants to change your device settings for GPS location"
    mLocationSettingsRequest = builder.build();
}
 
Example 5
Project: retro-reversi   File: SnapshotCoordinator.java   View source code 6 votes vote down vote up
@Override
public PendingResult<DeleteSnapshotResult> delete(GoogleApiClient googleApiClient,
                                                  final SnapshotMetadata snapshotMetadata) {
    if (!isAlreadyOpen(snapshotMetadata.getUniqueName()) &&
            !isAlreadyClosing(snapshotMetadata.getUniqueName())) {
        setIsClosing(snapshotMetadata.getUniqueName());
        try {
            return new CoordinatedPendingResult<>(
                    Games.Snapshots.delete(googleApiClient, snapshotMetadata),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            // deleted files are closed.
                            setClosed(snapshotMetadata.getUniqueName());
                        }
                    });
        } catch (RuntimeException e) {
            setClosed(snapshotMetadata.getUniqueName());
            throw e;
        }
    } else {
        throw new IllegalStateException(snapshotMetadata.getUniqueName() +
                " is either open or is busy");
    }
}
 
Example 6
Project: TFG-SmartU-La-red-social   File: FragmentMapa.java   View source code 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mBundle = savedInstanceState;
    if (getArguments() != null) {
        proyectos = getArguments().getParcelableArrayList(ARG_PROYECTOS);
    }
    //Para localizar al usuario inicializo la variable de la API de Google Maps
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(getContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
}
 
Example 7
Project: divertsy-client   File: SyncToDriveService.java   View source code 6 votes vote down vote up
public void ClearAccount(){
    Log.i(TAG, "Clearing Google API Account");
    GoogleApiClient mAPI = getGoogleApiClient();
    if (mAPI != null) {
        if(mAPI.isConnected()){
            mAPI.clearDefaultAccountAndReconnect();
            Log.i(TAG, "Clear account and reconnect called");
        } else {
            Log.w(TAG, "Google API client not connected when attempting disconnect");
            Toast.makeText(this, "Google API not connected. Make sure WiFi is On.", Toast.LENGTH_LONG).show();
        }
    } else {
        Log.w(TAG, "Google API was null when attempting to disconnect account");
    }
    stopSelf(mStartID);
}
 
Example 8
Project: penguins-in-space   File: Example.java   View source code 6 votes vote down vote up
@Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

  // Create the Google Api Client with access to Games
  mGoogleApiClient = new GoogleApiClient.Builder(this)
      .addConnectionCallbacks(this)
      .addOnConnectionFailedListener(this)
      .addApi(Games.API).addScope(Games.SCOPE_GAMES)
      .build();

  // set up a click listener for everything we care about
  for (int id : CLICKABLES) {
    findViewById(id).setOnClickListener(this);
  }
}
 
Example 9
Project: gdx-gamesvcs   File: GpgsClient.java   View source code 6 votes vote down vote up
/**
 * Initializes the GoogleApiClient. Give your main AndroidLauncher as context.
 * <p>
 * Don't forget to add onActivityResult method there with call to onGpgsActivityResult.
 *
 * @param context        your AndroidLauncher class
 * @param enableDriveAPI true if you activate save gamestate feature
 * @return this for method chunking
 */
public GpgsClient initialize(Activity context, boolean enableDriveAPI) {

    if (mGoogleApiClient != null)
        throw new IllegalStateException("Already initialized.");

    myContext = context;
    // retry some times when connect fails (needed when game state sync is enabled)
    firstConnectAttempt = MAX_CONNECTFAIL_RETRIES;

    GoogleApiClient.Builder builder = new GoogleApiClient.Builder(myContext)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Games.API).addScope(Games.SCOPE_GAMES);

    driveApiEnabled = enableDriveAPI;
    if (driveApiEnabled)
        builder.addApi(Drive.API).addScope(Drive.SCOPE_APPFOLDER);

    // add other APIs and scopes here as needed

    mGoogleApiClient = builder.build();

    return this;
}
 
Example 10
Project: SampleAppArch   File: LoginActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
      .requestEmail()
      .build();
  mGoogleApiClient = new GoogleApiClient.Builder(this)
      .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
      .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
      .build();
  initUI();
  if (loginViewModel.isLogin()) {
    showProgress(true);
    Single.timer(1, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(s -> {
          finish();
          startActivity(new Intent(LoginActivity.this, AppArchNavigationDrawer.class));
        });
  } else {
    loginView();
  }
}
 
Example 11
Project: androidadvanced   File: MainActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ButterKnife.bind(this);

    // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    }
}
 
Example 12
Project: Pocket-Plays-for-Twitch   File: BaseCastManager.java   View source code 6 votes vote down vote up
private void setDevice(CastDevice device) {
    mSelectedCastDevice = device;
    mDeviceName = mSelectedCastDevice.getFriendlyName();

    if (mApiClient == null) {
        LOGD(TAG, "acquiring a connection to Google Play services for " + mSelectedCastDevice);
        Cast.CastOptions.Builder apiOptionsBuilder = getCastOptionBuilder(mSelectedCastDevice);
        mApiClient = new GoogleApiClient.Builder(mContext)
                .addApi(Cast.API, apiOptionsBuilder.build())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mApiClient.connect();
    } else if (!mApiClient.isConnected() && !mApiClient.isConnecting()) {
        mApiClient.connect();
    }
}
 
Example 13
Project: Android_watch_magpie   File: Home_activity.java   View source code 6 votes vote down vote up
private void initView()
{
    fragmentAlert =new Fragment_display_alertes();
    fragmentMeasures=new Fragment_display_measures();
    fragmentSettings =new Fragment_display_settings();


    //add the fragment to the fragment manager
    getSupportFragmentManager().beginTransaction().add(R.id.main_container,fragmentAlert,"alertFrag").commit();
    getSupportFragmentManager().beginTransaction().add(R.id.main_container,fragmentMeasures,"measureFrag").commit();
    getSupportFragmentManager().beginTransaction().add(R.id.main_container,fragmentSettings,"settingsFrag").commit();


    //INIT the googe client
    googleClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

}
 
Example 14
Project: thesis-project   File: CriteriaMidtermInputActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.teacher_gradingfactor_activity_midterm);
    try {
        subject = subjectService.getSubjectById(getIntent().getExtras().getLong("subjectId"));
        formula = formulaService.getFormulaById(getIntent().getExtras().getLong("formulaId"));
        teacher = new TeacherHelper(this).loadUser().get();
        isExist = getIntent().getExtras().getBoolean("isExist");

        init();

        ArrayAdapter<String> spinnerAdapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, values);
        spinnerm.setAdapter(spinnerAdapter);

    } catch (Exception e) {
        e.printStackTrace();
    }

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
 
Example 15
Project: OpenOrbitCNCAndroidFrontend   File: SigninActivity.java   View source code 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Urbino.instance().getAppGraph().inject(this);
    signinPresenter.attachView(this);

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .requestProfile()
            .build();

    googleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this::onFailApiClientFail)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

    signInButton.setSize(SignInButton.SIZE_STANDARD);
    signInButton.setOnClickListener(this::onSignInClick);

}
 
Example 16
Project: Pickr   File: DataManager.java   View source code 6 votes vote down vote up
public Observable<PointOfInterest> getCompleteResult(final GoogleApiClient mGoogleApiClient, final String id) {
    return Observable.create(new Observable.OnSubscribe<PointOfInterest>() {
        @Override
        public void call(final Subscriber<? super PointOfInterest> subscriber) {
            final PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
                    .getPlaceById(mGoogleApiClient, id);
            placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
                @Override
                public void onResult(PlaceBuffer places) {
                    if (!places.getStatus().isSuccess()) {
                        places.release();
                        subscriber.onError(null);
                    } else {
                        subscriber.onNext(PointOfInterest.fromPlace(places.get(0)));
                        places.close();
                        subscriber.onCompleted();
                    }
                }
            });
        }
    });
}
 
Example 17
Project: cordova-plugin-firebase-performance-ka   File: FirebaseAuthenticationPlugin.java   View source code 6 votes vote down vote up
@Override
protected void pluginInitialize() {
    Log.d(TAG, "Starting Firebase Authentication plugin");

    this.firebaseAuth = FirebaseAuth.getInstance();
    this.phoneAuthProvider = PhoneAuthProvider.getInstance();

    Context context = this.cordova.getActivity().getApplicationContext();
    String defaultClientId = getDefaultClientId(context);
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(defaultClientId)
            .requestEmail()
            .requestProfile()
            .build();

    googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    googleApiClient.connect();
    //firebaseAuth = FirebaseAuth.getInstance();
    //firebaseAuth.addAuthStateListener(this);
}
 
Example 18
Project: androidthings-kuman-sm9   File: GoogleApiClientRepository.java   View source code 6 votes vote down vote up
private void setupGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(mApplication)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(@Nullable Bundle bundle) {
                    Timber.d("onConnected: advertises on the network as the host");
                    startNearbyConnectionsAdvertising();
                }

                @Override
                public void onConnectionSuspended(int cause) {
                    Timber.d("onConnectionSuspended: %s", cause);
                    mGoogleApiClient.reconnect();
                }
            })
            .addOnConnectionFailedListener(connectionResult -> Timber.e("onConnectionFailed: %s", connectionResult))
            .addApi(Nearby.CONNECTIONS_API)
            .build();
}
 
Example 19
Project: Hexpert   File: SnapshotCoordinator.java   View source code 5 votes vote down vote up
@Override
public PendingResult<OpenSnapshotResult> open(GoogleApiClient googleApiClient,
                                              final String filename, boolean createIfNotFound) {
    // check if the file is already open
    if (!isAlreadyOpen(filename)) {
        setIsOpening(filename);
        try {
            return new CoordinatedPendingResult<>(
                    Games.Snapshots.open(googleApiClient, filename, createIfNotFound),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            // if open failed, set the file to closed, otherwise, keep it open.
                            if (!result.getStatus().isSuccess()) {
                                Log.d(TAG, "Open was not a success: " +
                                        result.getStatus() + " for filename " + filename);
                                setClosed(filename);
                            } else {
                                Log.d(TAG, "Open successful: " + filename);
                            }
                        }
                    });
        } catch (RuntimeException e) {
            // catch runtime exceptions here - they should not happen, but they do.
            // mark the file as closed so it can be attempted to be opened again.
            setClosed(filename);
            throw e;
        }
    } else {
        // a more sophisticated solution could attach this operation to a future
        // that would be triggered by closing the file, but this will at least avoid
        // corrupting the data with non-resolvable conflicts.
        throw new IllegalStateException(filename + " is already open");
    }
}
 
Example 20
Project: penguins-in-space   File: SnapshotCoordinator.java   View source code 5 votes vote down vote up
@Override
public PendingResult<OpenSnapshotResult> open(GoogleApiClient googleApiClient,
                                              final SnapshotMetadata snapshotMetadata,
                                              int conflictPolicy) {
    // check if the file is already open
    if (!isAlreadyOpen(snapshotMetadata.getUniqueName())) {
        setIsOpening(snapshotMetadata.getUniqueName());
        try {
            return new CoordinatedPendingResult<>(Games.Snapshots.open(
                    googleApiClient, snapshotMetadata, conflictPolicy),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            // if open failed, set the file to closed, otherwise, keep it open.
                            if (!result.getStatus().isSuccess()) {
                                Log.d(TAG, "Open was not a success: " +
                                        result.getStatus() + " for filename " +
                                        snapshotMetadata.getUniqueName());
                                setClosed(snapshotMetadata.getUniqueName());
                            } else {
                                Log.d(TAG, "Open was successful: " +
                                        snapshotMetadata.getUniqueName());
                            }
                        }
                    });
        } catch (RuntimeException e) {
            setClosed(snapshotMetadata.getUniqueName());
            throw e;
        }
    } else {
        throw new IllegalStateException(snapshotMetadata.getUniqueName() + " is already open");
    }
}
 
Example 21
Project: Asteroid   File: SnapshotCoordinator.java   View source code 5 votes vote down vote up
@Override
public PendingResult<OpenSnapshotResult> resolveConflict(GoogleApiClient googleApiClient,
                                                         String conflictId,
                                                         final Snapshot snapshot) {
    if (!isAlreadyOpen(snapshot.getMetadata().getUniqueName()) &&
            !isAlreadyClosing(snapshot.getMetadata().getUniqueName())) {
        setIsOpening(snapshot.getMetadata().getUniqueName());
        try {
            return new CoordinatedPendingResult<>(
                    Games.Snapshots.resolveConflict(googleApiClient, conflictId, snapshot),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            if (!result.getStatus().isSuccess()) {
                                setClosed(snapshot.getMetadata().getUniqueName());
                            }
                        }
                    });
        } catch (RuntimeException e) {
            setClosed(snapshot.getMetadata().getUniqueName());
            throw e;
        }
    } else {
        throw new IllegalStateException(snapshot.getMetadata().getUniqueName() +
                " is already open or is busy");
    }
}
 
Example 22
Project: mapbox-events-android   File: GoogleLocationEngine.java   View source code 5 votes vote down vote up
private GoogleLocationEngine(Context context) {
  super();
  this.context = new WeakReference<>(context);
  googleApiClient = new GoogleApiClient.Builder(this.context.get())
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .build();
}
 
Example 23
Project: chromium-for-android-56-debug-video   File: CreateRouteRequest.java   View source code 5 votes vote down vote up
private GoogleApiClient createApiClient(Cast.Listener listener, Context context) {
    Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions
            .builder(mSink.getDevice(), listener)
            // TODO(avayvod): hide this behind the flag or remove
            .setVerboseLoggingEnabled(true);

    return new GoogleApiClient.Builder(context)
            .addApi(Cast.API, apiOptionsBuilder.build())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}
 
Example 24
Project: iSPY   File: MapsActivity2.java   View source code 5 votes vote down vote up
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}
 
Example 25
Project: feup-lpoo-armadillo   File: GameHelper.java   View source code 5 votes vote down vote up
/**
 * Returns the GoogleApiClient object. In order to call this method, you
 * must have called @link{setup}.
 */
public GoogleApiClient getApiClient() {
    if (mGoogleApiClient == null) {
        throw new IllegalStateException(
                "No GoogleApiClient. Did you call setup()?");
    }
    return mGoogleApiClient;
}
 
Example 26
Project: Botanist   File: AccountActivity.java   View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_account);
    mController = new AccountController(this);
    mAuth = FirebaseAuth.getInstance();
    mAuthListener = new FirebaseAuth.AuthStateListener() {

        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            }
            else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
                signOut();
            }
        }
    };
    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail().requestIdToken(getString(R.string.default_web_client_id)).build();
    // Build a GoogleApiClient with access to the Google Sign-In API and the options specified by gso.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
}
 
Example 27
Project: Excuser   File: WearShakeIntensityFragment.java   View source code 5 votes vote down vote up
private void setGoogleApiClient(){
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}
 
Example 28
Project: MapsWithPlacesAutoComplete   File: MapsActivity.java   View source code 5 votes vote down vote up
protected synchronized void buildGoogleAPiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addOnConnectionFailedListener(this)
            .addConnectionCallbacks(this)
            .addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API)
            .build();
}
 
Example 29
Project: GitHub   File: ReactiveLocationProvider.java   View source code 5 votes vote down vote up
/**
 * Returns observable that fetches current place from Places API. To flatmap and auto release
 * buffer to {@link com.google.android.gms.location.places.PlaceLikelihood} observable use
 * {@link DataBufferObservable}.
 *
 * @param placeFilter filter
 * @return observable that emits current places buffer and completes
 */
public Observable<PlaceLikelihoodBuffer> getCurrentPlace(@Nullable final PlaceFilter placeFilter) {
    return getGoogleApiClientObservable(Places.PLACE_DETECTION_API, Places.GEO_DATA_API)
            .flatMap(new Func1<GoogleApiClient, Observable<PlaceLikelihoodBuffer>>() {
                @Override
                public Observable<PlaceLikelihoodBuffer> call(GoogleApiClient api) {
                    return fromPendingResult(Places.PlaceDetectionApi.getCurrentPlace(api, placeFilter));
                }
            });
}
 
Example 30
Project: GitHub   File: ReactiveLocationProvider.java   View source code 5 votes vote down vote up
/**
 * Returns observable that fetches a place from the Places API using the place ID.
 *
 * @param placeId id for place
 * @return observable that emits places buffer and completes
 */
public Observable<PlaceBuffer> getPlaceById(@Nullable final String placeId) {
    return getGoogleApiClientObservable(Places.PLACE_DETECTION_API, Places.GEO_DATA_API)
            .flatMap(new Func1<GoogleApiClient, Observable<PlaceBuffer>>() {
                @Override
                public Observable<PlaceBuffer> call(GoogleApiClient api) {
                    return fromPendingResult(Places.GeoDataApi.getPlaceById(api, placeId));
                }
            });
}
 
Example 31
Project: retro-reversi   File: GameHelper.java   View source code 5 votes vote down vote up
/**
 * Creates a GoogleApiClient.Builder for use with @link{#setup}. Normally,
 * you do not have to do this; use this method only if you need to make
 * nonstandard setup (e.g. adding extra scopes for other APIs) on the
 * GoogleApiClient.Builder before calling @link{#setup}.
 */
public GoogleApiClient.Builder createApiClientBuilder() {
    if (mSetupDone) {
        String error = "GameHelper: you called GameHelper.createApiClientBuilder() after "
                + "calling setup. You can only get a client builder BEFORE performing setup.";
        logError(error);
        throw new IllegalStateException(error);
    }

    GoogleApiClient.Builder builder = new GoogleApiClient.Builder(
            mActivity, this, this);

    if (0 != (mRequestedClients & CLIENT_GAMES)) {
        builder.addApi(Games.API, mGamesApiOptions);
        builder.addScope(Games.SCOPE_GAMES);
    }

    if (0 != (mRequestedClients & CLIENT_PLUS)) {
        builder.addApi(Plus.API);
        builder.addScope(Plus.SCOPE_PLUS_LOGIN);
    }

    if (0 != (mRequestedClients & CLIENT_SNAPSHOT)) {
      builder.addScope(Drive.SCOPE_APPFOLDER);
      builder.addApi(Drive.API);
    }

    mGoogleApiClientBuilder = builder;
    return builder;
}
 
Example 32
Project: GitHub   File: ReactiveLocationProvider.java   View source code 5 votes vote down vote up
/**
 * Returns observable that fetches a placePhotoMetadata from the Places API using the place placePhotoMetadata metadata.
 * Use after fetching the place placePhotoMetadata metadata with {@link ReactiveLocationProvider#getPhotoMetadataById(String)}
 *
 * @param placePhotoMetadata the place photo meta data
 * @return observable that emits the photo result and completes
 */
public Observable<PlacePhotoResult> getPhotoForMetadata(final PlacePhotoMetadata placePhotoMetadata) {
    return getGoogleApiClientObservable(Places.PLACE_DETECTION_API, Places.GEO_DATA_API)
            .flatMap(new Func1<GoogleApiClient, Observable<PlacePhotoResult>>() {
                @Override
                public Observable<PlacePhotoResult> call(GoogleApiClient api) {
                    return fromPendingResult(placePhotoMetadata.getPhoto(api));
                }
            });
}
 
Example 33
Project: S3-16-simone   File: GoogleApiHelper.java   View source code 5 votes vote down vote up
/**
 * Initialization of the GoogleApiClient with Callbacks, Listeners and View for popups.
 * @param activity
 * @param view
 */
public void buildGoogleApiClient(FullscreenBaseGameActivity activity, View view) {
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(activity)
            .addOnConnectionFailedListener(activity)
            .addScope(Games.SCOPE_GAMES)
            .setViewForPopups(view)
            .addApi(Games.API).build();
    mGoogleApiClient.connect();
}
 
Example 34
Project: SpaceRace   File: SnapshotCoordinator.java   View source code 5 votes vote down vote up
@Override
public PendingResult<OpenSnapshotResult> open(GoogleApiClient googleApiClient,
                                              final SnapshotMetadata snapshotMetadata,
                                              int conflictPolicy) {
    // check if the file is already open
    if (!isAlreadyOpen(snapshotMetadata.getUniqueName())) {
        setIsOpening(snapshotMetadata.getUniqueName());
        try {
            return new CoordinatedPendingResult<>(Games.Snapshots.open(
                    googleApiClient, snapshotMetadata, conflictPolicy),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            // if open failed, set the file to closed, otherwise, keep it open.
                            if (!result.getStatus().isSuccess()) {
                                Log.d(TAG, "Open was not a success: " +
                                        result.getStatus() + " for filename " +
                                        snapshotMetadata.getUniqueName());
                                setClosed(snapshotMetadata.getUniqueName());
                            } else {
                                Log.d(TAG, "Open was successful: " +
                                        snapshotMetadata.getUniqueName());
                            }
                        }
                    });
        } catch (RuntimeException e) {
            setClosed(snapshotMetadata.getUniqueName());
            throw e;
        }
    } else {
        throw new IllegalStateException(snapshotMetadata.getUniqueName() + " is already open");
    }
}
 
Example 35
Project: Hexpert   File: SnapshotCoordinator.java   View source code 5 votes vote down vote up
@Override
public PendingResult<OpenSnapshotResult> open(GoogleApiClient googleApiClient,
                                              final SnapshotMetadata snapshotMetadata,
                                              int conflictPolicy) {
    // check if the file is already open
    if (!isAlreadyOpen(snapshotMetadata.getUniqueName())) {
        setIsOpening(snapshotMetadata.getUniqueName());
        try {
            return new CoordinatedPendingResult<>(Games.Snapshots.open(
                    googleApiClient, snapshotMetadata, conflictPolicy),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            // if open failed, set the file to closed, otherwise, keep it open.
                            if (!result.getStatus().isSuccess()) {
                                Log.d(TAG, "Open was not a success: " +
                                        result.getStatus() + " for filename " +
                                        snapshotMetadata.getUniqueName());
                                setClosed(snapshotMetadata.getUniqueName());
                            } else {
                                Log.d(TAG, "Open was successful: " +
                                        snapshotMetadata.getUniqueName());
                            }
                        }
                    });
        } catch (RuntimeException e) {
            setClosed(snapshotMetadata.getUniqueName());
            throw e;
        }
    } else {
        throw new IllegalStateException(snapshotMetadata.getUniqueName() + " is already open");
    }
}
 
Example 36
Project: androidadvanced   File: MainActivity.java   View source code 5 votes vote down vote up
private void setupGoogleAPIClient() {
    if (googleApiClient == null) {
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
}
 
Example 37
Project: TripleTap   File: SnapshotCoordinator.java   View source code 5 votes vote down vote up
@Override
public PendingResult<OpenSnapshotResult> resolveConflict(GoogleApiClient googleApiClient,
                                                         String conflictId,
                                                         final Snapshot snapshot) {
    if (!isAlreadyOpen(snapshot.getMetadata().getUniqueName()) &&
            !isAlreadyClosing(snapshot.getMetadata().getUniqueName())) {
        setIsOpening(snapshot.getMetadata().getUniqueName());
        try {
            return new CoordinatedPendingResult<>(
                    Games.Snapshots.resolveConflict(googleApiClient, conflictId, snapshot),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            if (!result.getStatus().isSuccess()) {
                                setClosed(snapshot.getMetadata().getUniqueName());
                            }
                        }
                    });
        } catch (RuntimeException e) {
            setClosed(snapshot.getMetadata().getUniqueName());
            throw e;
        }
    } else {
        throw new IllegalStateException(snapshot.getMetadata().getUniqueName() +
                " is already open or is busy");
    }
}
 
Example 38
Project: penguins-in-space   File: SnapshotCoordinator.java   View source code 5 votes vote down vote up
@Override
public PendingResult<OpenSnapshotResult> open(GoogleApiClient googleApiClient,
                                              final SnapshotMetadata snapshotMetadata) {
    // check if the file is already open
    if (!isAlreadyOpen(snapshotMetadata.getUniqueName())) {
        setIsOpening(snapshotMetadata.getUniqueName());
        try {
            return new CoordinatedPendingResult<>(
                    Games.Snapshots.open(googleApiClient, snapshotMetadata),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            // if open failed, set the file to closed, otherwise, keep it open.
                            if (!result.getStatus().isSuccess()) {
                                Log.d(TAG, "Open was not a success: " +
                                        result.getStatus() + " for filename " +
                                        snapshotMetadata.getUniqueName());
                                setClosed(snapshotMetadata.getUniqueName());
                            } else {
                                Log.d(TAG, "Open was successful: " +
                                        snapshotMetadata.getUniqueName());
                            }
                        }
                    });
        } catch (RuntimeException e) {
            setClosed(snapshotMetadata.getUniqueName());
            throw e;
        }
    } else {
        throw new IllegalStateException(snapshotMetadata.getUniqueName() + " is already open");
    }
}
 
Example 39
Project: Hexpert   File: SnapshotCoordinator.java   View source code 5 votes vote down vote up
@Override
public PendingResult<OpenSnapshotResult> resolveConflict(GoogleApiClient googleApiClient,
                                                         String conflictId,
                                                         final Snapshot snapshot) {
    if (!isAlreadyOpen(snapshot.getMetadata().getUniqueName()) &&
            !isAlreadyClosing(snapshot.getMetadata().getUniqueName())) {
        setIsOpening(snapshot.getMetadata().getUniqueName());
        try {
            return new CoordinatedPendingResult<>(
                    Games.Snapshots.resolveConflict(googleApiClient, conflictId, snapshot),
                    new ResultListener() {
                        @Override
                        public void onResult(Result result) {
                            if (!result.getStatus().isSuccess()) {
                                setClosed(snapshot.getMetadata().getUniqueName());
                            }
                        }
                    });
        } catch (RuntimeException e) {
            setClosed(snapshot.getMetadata().getUniqueName());
            throw e;
        }
    } else {
        throw new IllegalStateException(snapshot.getMetadata().getUniqueName() +
                " is already open or is busy");
    }
}
 
Example 40
Project: GitHub   File: RemoveGeofenceRequestIdsObservable.java   View source code 5 votes vote down vote up
@Override
protected void removeGeofences(GoogleApiClient locationClient, final Observer<? super Status> observer) {
    LocationServices.GeofencingApi.removeGeofences(locationClient, geofenceRequestIds)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        observer.onNext(status);
                        observer.onCompleted();
                    } else {
                        observer.onError(new StatusException(status));
                    }
                }
            });
}