com.google.android.gms.common.api.Status Java Examples

The following examples show how to use com.google.android.gms.common.api.Status. 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: GoogleSignInListenerTest.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@Test
public void onActivityResult_validRequestCode_apiException() throws Throwable {
    // Given
    FuturePromise promise = Mockito.mock(FuturePromise.class);
    GoogleSignInListener listener = new GoogleSignInListener(promise);
    Intent intent = PowerMockito.mock(Intent.class);
    int requestCode = Const.GOOGLE_SIGN_IN;
    int resultCode = -1;
    final Task task = Mockito.mock(Task.class);
    Mockito.when(task.getResult(ApiException.class)).then(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            throw new ApiException(Status.RESULT_CANCELED);
        }
    });
    Mockito.when(GoogleSignIn.getSignedInAccountFromIntent(Mockito.any(Intent.class))).thenReturn(task);

    // When
    listener.onActivityResult(requestCode, resultCode, intent);

    // Then
    Mockito.verify(((AndroidApplication) Gdx.app), VerificationModeFactory.times(1)).removeAndroidEventListener(Mockito.refEq(listener));
    Mockito.verify(promise, VerificationModeFactory.times(1)).doFail(Mockito.nullable(Exception.class));
}
 
Example #2
Source File: AutocompleteTestActivity.java    From android-places-demos with Apache License 2.0 6 votes vote down vote up
/**
 * Called when AutocompleteActivity finishes
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
  if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
    if (resultCode == AutocompleteActivity.RESULT_OK) {
      Place place = Autocomplete.getPlaceFromIntent(intent);
      responseView.setText(
          StringUtil.stringifyAutocompleteWidget(place, isDisplayRawResultsChecked()));
    } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
      Status status = Autocomplete.getStatusFromIntent(intent);
      responseView.setText(status.getStatusMessage());
    } else if (resultCode == AutocompleteActivity.RESULT_CANCELED) {
      // The user canceled the operation.
    }
  }

  // Required because this class extends AppCompatActivity which extends FragmentActivity
  // which implements this method to pass onActivityResult calls to child fragments
  // (eg AutocompleteFragment).
  super.onActivityResult(requestCode, resultCode, intent);
}
 
Example #3
Source File: BaseCastManager.java    From UTubeTV with The Unlicense 6 votes vote down vote up
/**
 * Stops the application on the receiver device.
 */
public void stopApplication() throws IllegalStateException, IOException, TransientNetworkDisconnectionException, NoConnectionException {
  checkConnectivity();
  Cast.CastApi.stopApplication(mApiClient).setResultCallback(new ResultCallback<Status>() {

    @Override
    public void onResult(Status result) {
      if (!result.isSuccess()) {
        CastUtils.LOGD(TAG, "stopApplication -> onResult: stopping " + "application failed");
        onApplicationStopFailed(result.getStatusCode());
      } else {
        CastUtils.LOGD(TAG, "stopApplication -> onResult Stopped application " + "successfully");
      }
    }
  });
}
 
Example #4
Source File: DataCastManager.java    From android with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the <code>message</code> on the data channel for the <code>namespace</code>. If fails,
 * it will call <code>onMessageSendFailed</code>
 *
 * @param message
 * @param namespace
 * @throws NoConnectionException If no connectivity to the device exists
 * @throws TransientNetworkDisconnectionException If framework is still trying to recover from a
 *             possibly transient loss of network
 * @throws IllegalArgumentException If the the message is null, empty, or too long; or if the
 *             namespace is null or too long.
 * @throws IllegalStateException If there is no active service connection.
 * @throws IOException
 */
public void sendDataMessage(String message, String namespace)
        throws IllegalArgumentException, IllegalStateException, IOException,
        TransientNetworkDisconnectionException, NoConnectionException {
    checkConnectivity();
    if (TextUtils.isEmpty(namespace)) {
        throw new IllegalArgumentException("namespace cannot be empty");
    }
    Cast.CastApi.sendMessage(mApiClient, namespace, message).
            setResultCallback(new ResultCallback<Status>() {

                @Override
                public void onResult(Status result) {
                    if (!result.isSuccess()) {
                        DataCastManager.this.onMessageSendFailed(result);
                    }
                }
            });
}
 
Example #5
Source File: VideoCastManager.java    From android with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the <code>message</code> on the data channel for the namespace that was provided
 * during the initialization of this class. If <code>messageId &gt; 0</code>, then it has to be
 * a unique identifier for the message; this id will be returned if an error occurs. If
 * <code>messageId == 0</code>, then an auto-generated unique identifier will be created and
 * returned for the message.
 *
 * @param message
 * @return
 * @throws IllegalStateException                  If the namespace is empty or null
 * @throws NoConnectionException                  If no connectivity to the device exists
 * @throws TransientNetworkDisconnectionException If framework is still trying to recover from
 *                                                a possibly transient loss of network
 */
public void sendDataMessage(String message) throws TransientNetworkDisconnectionException,
        NoConnectionException {
    if (TextUtils.isEmpty(mDataNamespace)) {
        throw new IllegalStateException("No Data Namespace is configured");
    }
    checkConnectivity();
    Cast.CastApi.sendMessage(mApiClient, mDataNamespace, message)
            .setResultCallback(new ResultCallback<Status>() {

                @Override
                public void onResult(Status result) {
                    if (!result.isSuccess()) {
                        VideoCastManager.this.onMessageSendFailed(result.getStatusCode());
                    }
                }
            });
}
 
Example #6
Source File: ChromeCastService.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * ステータスに基づいて、レスポンスする.
 * @param response レスポンス
 * @param result Chromecastからの状態
 * @param message Chromecastの状態
 */
private void onChromeCastResult(final Intent response, final Status result, final String message) {
    if (result == null) {
        MessageUtils.setIllegalDeviceStateError(response, message);
    } else {
        if (result.isSuccess()) {
            response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_OK);
        } else {
            if (message == null) {
                MessageUtils.setIllegalDeviceStateError(response);
            } else {
                MessageUtils.setIllegalDeviceStateError(response, message + " is error");
            }
        }
    }
    sendResponse(response);
}
 
Example #7
Source File: GoogleFitSessionManagerTest.java    From JayPS-AndroidApp with MIT License 6 votes vote down vote up
private DataSet getDataSet() {
    ArrayList<Session> sessions = new ArrayList<>();
    sessions.add(_mockSession);

    ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
    verify(_mockResult, times(1)).setResultCallback(captor.capture());

    ArgumentCaptor<Session> sessionArgumentCaptor = ArgumentCaptor.forClass(Session.class);

    captor.getValue().onResult(new SessionStopResult(new Status(1), sessions));

    ArgumentCaptor<DataSet> dataSetArgumentCaptor = ArgumentCaptor.forClass(DataSet.class);
    verify(_mockPlayServices,times(1)).newSessionInsertRequest(sessionArgumentCaptor.capture(), dataSetArgumentCaptor.capture());
    assertEquals(_mockSession, sessionArgumentCaptor.getValue());

    return dataSetArgumentCaptor.getValue();
}
 
Example #8
Source File: CreateRouteRequest.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
public void onResult(Cast.ApplicationConnectionResult result) {
    if (mState != STATE_LAUNCHING_APPLICATION
            && mState != STATE_API_CONNECTION_SUSPENDED) {
        throwInvalidState();
    }

    Status status = result.getStatus();
    if (!status.isSuccess()) {
        Log.e(TAG, "Launch application failed with status: %s, %d, %s",
                mSource.getApplicationId(), status.getStatusCode(), status.getStatusMessage());
        reportError();
        return;
    }

    mState = STATE_LAUNCH_SUCCEEDED;
    reportSuccess(result);
}
 
Example #9
Source File: CastDeviceControllerImpl.java    From android_packages_apps_GmsCore with Apache License 2.0 6 votes vote down vote up
@Override
public void spontaneousEventReceived(ChromeCastSpontaneousEvent event) {
    switch (event.getType()) {
        case MEDIA_STATUS:
            break;
        case STATUS:
            su.litvak.chromecast.api.v2.Status status = (su.litvak.chromecast.api.v2.Status)event.getData();
            Application app = status.getRunningApp();
            ApplicationMetadata metadata = this.createMetadataFromApplication(app);
            if (app != null) {
                this.onApplicationStatusChanged(new ApplicationStatus(app.statusText));
            }
            int activeInputState = status.activeInput ? 1 : 0;
            int standbyState = status.standBy ? 1 : 0;
            this.onDeviceStatusChanged(new CastDeviceStatus(status.volume.level, status.volume.muted, activeInputState, metadata, standbyState));
            break;
        case APPEVENT:
            break;
        case CLOSE:
            this.onApplicationDisconnected(CommonStatusCodes.SUCCESS);
            break;
        default:
            break;
    }
}
 
Example #10
Source File: SignIn.java    From easygoogle with Apache License 2.0 6 votes vote down vote up
/**
 * Initiate the sign out and disconnect process. Results are returned to the
 * {@link pub.devrel.easygoogle.gac.SignIn.SignInListener}. If the user is not already signed
 * in or the sign out operation fails, no result will be returned.
 */
public void signOut() {
    Log.d(TAG, "signOut");
    final GacFragment fragment = getFragment();
    if (!fragment.isConnected()) {
        Log.w(TAG, "Can't sign out, not signed in!");
        return;
    }

    Auth.GoogleSignInApi.revokeAccess(fragment.getGoogleApiClient()).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    if (status.isSuccess()) {
                        getListener().onSignedOut();
                    } else {
                        Log.w(TAG, "Could not sign out: " + status);
                    }
                }
            });
}
 
Example #11
Source File: LocationSwitch.java    From react-native-location-switch with Apache License 2.0 6 votes vote down vote up
@Override
public void onResult(LocationSettingsResult result) {
    final Status status = result.getStatus();
    switch (status.getStatusCode()) {
        case LocationSettingsStatusCodes.SUCCESS:
            // All location settings are satisfied -> nothing to do
            callSuccessCallback();
            break;
        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
            // Location settings are not satisfied. Show the user a dialog to upgrade location settings
            try {
                // Show the dialog by calling startResolutionForResult(), and check the result
                status.startResolutionForResult(mActivity, REQUEST_CHECK_SETTINGS);
            } catch (IntentSender.SendIntentException e) {
                Log.e(TAG, "PendingIntent unable to execute request.", e);
                callErrorCallback();
            }
            break;
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
            Log.e(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
            callErrorCallback();
            break;
    }
}
 
Example #12
Source File: ChromeCastController.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Receiverアプリケーションを起動する.
 * 
 */
private void launchApplication() {
    if (mApiClient != null && mApiClient.isConnected()) {
        Cast.CastApi.launchApplication(mApiClient, mAppId)
            .setResultCallback((result) -> {
                Status status = result.getStatus();
                if (status.isSuccess()) {
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "launchApplication$onResult: Success");
                    }
                    for (int i = 0; i < mCallbacks.size(); i++) {
                        mCallbacks.get(i).onAttach();
                    }

                } else {
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "launchApplication$onResult: Fail");
                    }
                    teardown();
                }
                if (mResult != null) {
                    mResult.onChromeCastConnected();
                }
            });
    }
}
 
Example #13
Source File: MainActivity.java    From nearby-beacons with MIT License 6 votes vote down vote up
@Override
public void onResult(@NonNull Status status) {
    if (status.isSuccess()) {
        Log.i(TAG, "Permission status succeeded.");
        if (runOnSuccess != null) {
            runOnSuccess.run();
        }
    } else {
        // Currently, the only resolvable error is that the device is not opted
        // in to Nearby. Starting the resolution displays an opt-in dialog.
        if (status.hasResolution()) {
            try {
                status.startResolutionForResult(MainActivity.this,
                        REQUEST_RESOLVE_ERROR);
            } catch (IntentSender.SendIntentException e) {
                showToastAndLog(Log.ERROR, "Request failed with exception: " + e);
            }
        } else {
            showToastAndLog(Log.ERROR, "Request failed with : " + status);
        }
    }
}
 
Example #14
Source File: RxGoogleAuthFragment.java    From RxSocialAuth with Apache License 2.0 6 votes vote down vote up
/**
 * Handle google sign in result
 *
 * @param result the GoogleSignInResult result
 */
public void handleSignInResult(final GoogleSignInResult result) {
    if (result.isSuccess()) {
        GoogleSignInAccount account = result.getSignInAccount();
        mGoogleApiClient.disconnect();
        verifySmartLockIsEnabled(new RxAccount(account));
    }
    else {
        // delete credential
        if(mCredential != null) {
            Auth.CredentialsApi.delete(mGoogleApiClient, mCredential).setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    mGoogleApiClient.disconnect();
                    mAccountSubject.onError(new Throwable(result.getStatus().toString()));
                }
            });
        }
        else {
            mGoogleApiClient.disconnect();
            mAccountSubject.onError(new Throwable(result.getStatus().toString()));
        }
    }
}
 
Example #15
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void registerFitnessDataListener(DataSource dataSource, DataType dataType) {

        SensorRequest request = new SensorRequest.Builder()
                .setDataSource( dataSource )
                .setDataType( dataType )
                .setSamplingRate( 3, TimeUnit.SECONDS )
                .build();

        Fitness.SensorsApi.add(mApiClient, request, this)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        if (status.isSuccess()) {
                            Log.e("GoogleFit", "SensorApi successfully added");
                        } else {
                            Log.e("GoogleFit", "adding status: " + status.getStatusMessage());
                        }
                    }
                });
    }
 
Example #16
Source File: RobocarDiscoverer.java    From robocar with Apache License 2.0 6 votes vote down vote up
public void acceptConnection() {
    final RobocarConnection connection = mRobocarConnectionLiveData.getValue();
    if (connection == null) {
        return;
    }

    connection.setState(ConnectionState.AUTH_ACCEPTED);
    acceptConnection(connection.getEndpointId())
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    if (status.isSuccess()) {
                        Log.d(TAG, "Accepted connection.");
                    } else {
                        Log.d(TAG, String.format("Accept unsuccessful. %d %s",
                                status.getStatusCode(), status.getStatusMessage()));
                        // revert state
                        connection.setState(ConnectionState.AUTHENTICATING);
                    }
                }
            });
}
 
Example #17
Source File: SmartLock.java    From easygoogle with Apache License 2.0 6 votes vote down vote up
/**
 * Show the dialog allowing the user to choose a Credential. This method shoud only be called
 * after you receive the {@link SmartLockListener#onShouldShowCredentialPicker()} callback.
 */
public void showCredentialPicker() {
    CredentialRequest request = buildCredentialRequest();
    Activity activity = getFragment().getActivity();
    int maskedCode = getFragment().maskRequestCode(RC_READ);

    Auth.CredentialsApi.request(getFragment().getGoogleApiClient(), request)
            .setResultCallback(new ResolvingResultCallbacks<CredentialRequestResult>(activity, maskedCode) {
                @Override
                public void onSuccess(CredentialRequestResult result) {
                    getListener().onCredentialRetrieved(result.getCredential());
                }

                @Override
                public void onUnresolvableFailure(Status status) {
                    Log.e(TAG, "showCredentialPicker:onUnresolvableFailure:" + status);
                }
            });
}
 
Example #18
Source File: RxSmartLockPasswordsFragment.java    From RxSocialAuth with Apache License 2.0 5 votes vote down vote up
private void disableAutoSignIn() {
    Auth.CredentialsApi.disableAutoSignIn(mCredentialsApiClient).setResultCallback(new ResultCallback<Status>() {
        @Override
        public void onResult(@NonNull Status status) {
            mCredentialsApiClient.disconnect();
            mStatusSubject.onNext(new RxStatus(status));
            mStatusSubject.onCompleted();
        }
    });
}
 
Example #19
Source File: LocationRemoveUpdatesSingleOnSubscribe.java    From RxGps with Apache License 2.0 5 votes vote down vote up
@Override
protected void onGoogleApiClientReady(GoogleApiClient apiClient, SingleEmitter<Status> emitter) {
    setupLocationPendingResult(
            LocationServices.FusedLocationApi.removeLocationUpdates(apiClient, pendingIntent),
            SingleResultCallBack.get(emitter)
    );
}
 
Example #20
Source File: LocationSettingsActivity.java    From RxGps with Apache License 2.0 5 votes vote down vote up
void handleIntent() {
    Status status = getIntent().getParcelableExtra(ARG_STATUS);

    try {
        status.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
    } catch (IntentSender.SendIntentException | NullPointerException e) {

        setResolutionResultAndFinish(Activity.RESULT_CANCELED);
    }
}
 
Example #21
Source File: GatewayTest.java    From gateway-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleGooglePayResultCallsError() {
    int requestCode = Gateway.REQUEST_GOOGLE_PAY_LOAD_PAYMENT_DATA;
    int resultCode = AutoResolveHelper.RESULT_ERROR;

    // mock autoresolvehelper method
    Status mockStatus = mock(Status.class);
    Intent mockData = mock(Intent.class);
    doReturn(mockStatus).when(mockData).getParcelableExtra("com.google.android.gms.common.api.AutoResolveHelper.status");

    GatewayGooglePayCallback callback = spy(new GatewayGooglePayCallback() {
        @Override
        public void onReceivedPaymentData(JSONObject paymentData) {
            fail("Should not have received payment data");
        }

        @Override
        public void onGooglePayCancelled() {
            fail("Should not have called cancelled");
        }

        @Override
        public void onGooglePayError(Status status) {
            assertEquals(mockStatus, status);
        }
    });

    boolean result = Gateway.handleGooglePayResult(requestCode, resultCode, mockData, callback);

    assertTrue(result);
    verify(callback).onGooglePayError(any());
}
 
Example #22
Source File: MainActivity.java    From android-play-places with Apache License 2.0 5 votes vote down vote up
/**
 * Called after the autocomplete activity has finished to return its result.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Check that the result was from the autocomplete widget.
    if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
        if (resultCode == RESULT_OK) {
            // Get the user's selected place from the Intent.
            Place place = PlaceAutocomplete.getPlace(this, data);
            Log.i(TAG, "Place Selected: " + place.getName());

            // Format the place's details and display them in the TextView.
            mPlaceDetailsText.setText(formatPlaceDetails(getResources(), place.getName(),
                    place.getId(), place.getAddress(), place.getPhoneNumber(),
                    place.getWebsiteUri()));

            // Display attributions if required.
            CharSequence attributions = place.getAttributions();
            if (!TextUtils.isEmpty(attributions)) {
                mPlaceAttribution.setText(Html.fromHtml(attributions.toString()));
            } else {
                mPlaceAttribution.setText("");
            }
        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(this, data);
            Log.e(TAG, "Error: Status = " + status.toString());
        } else if (resultCode == RESULT_CANCELED) {
            // Indicates that the activity closed before a selection was made. For example if
            // the user pressed the back button.
        }
    }
}
 
Example #23
Source File: FitResultCallback.java    From android-play-games-in-motion with Apache License 2.0 5 votes vote down vote up
private void onSessionUnsubscription(Status status) {
    if (status.isSuccess()) {
        Utils.logDebug(TAG, "Ended data session.");
    } else {
        Utils.logDebug(TAG, "Unable to end data session.");
    }
}
 
Example #24
Source File: LocationFragment.java    From android with Apache License 2.0 5 votes vote down vote up
protected IntentSender getLocationResolution() {
    if (!hasLocationResolution()) return null;

    Status status = mLocationDisabledException.getStatus();
    PendingIntent pi = status.getResolution();

    return pi.getIntentSender();
}
 
Example #25
Source File: Leaderboards.java    From godot-gpgs with MIT License 5 votes vote down vote up
public void getLeaderboardValue(final String id) {
     if (googleApiClient == null || !googleApiClient.isConnected()) return;
     activity.runOnUiThread(new Runnable() {
	@Override
         public void run() {
             Games.Leaderboards.loadCurrentPlayerLeaderboardScore(googleApiClient, id, LeaderboardVariant.TIME_SPAN_ALL_TIME, LeaderboardVariant.COLLECTION_PUBLIC).setResultCallback(new ResultCallback<LoadPlayerScoreResult>() {
                 @Override
                 public void onResult(LoadPlayerScoreResult result) {
                     Status status = result.getStatus();
                     if (status.getStatusCode() == GamesStatusCodes.STATUS_OK) {
                         LeaderboardScore score = result.getScore();
                         if (score != null) {
                             int scoreValue = (int) score.getRawScore();
                             Log.d(TAG, "GPGS: Leaderboard values is " + score.getDisplayScore());
                             GodotLib.calldeferred(instance_id, "_on_leaderboard_get_value", new Object[]{ scoreValue, id });
                         } else {
                             Log.d(TAG, "GPGS: getLeaderboardValue STATUS_OK but is NULL -> Request again...");
                             getLeaderboardValue(id);
                         }
                     } else if (status.getStatusCode() == GamesStatusCodes.STATUS_CLIENT_RECONNECT_REQUIRED) {
                         Log.d(TAG, "GPGS: getLeaderboardValue reconnect required -> reconnecting...");
                         googleApiClient.reconnect();
                     } else {
                         Log.d(TAG, "GPGS: getLeaderboardValue connection error -> " + status.getStatusMessage());
                         GodotLib.calldeferred(instance_id, "_on_leaderboard_get_value_error", new Object[]{ id });
                     }
                 }
             });
             Log.d(TAG, "GPGS: getLeaderboardValue '" + id + "'.");
	}
});
 }
 
Example #26
Source File: PhoneNumberVerifier.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent == null) {
        return;
    }

    String action = intent.getAction();
    if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(action)) {
        cancelTimeout();
        notifyStatus(STATUS_RESPONSE_RECEIVED, null);
        Bundle extras = intent.getExtras();
        Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
        switch(status.getStatusCode()) {
            case CommonStatusCodes.SUCCESS:
                String smsMessage = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
                Log.d(TAG, "Retrieved sms code: " + smsMessage);
                if (smsMessage != null) {
                    verifyMessage(smsMessage);
                }
                break;
            case CommonStatusCodes.TIMEOUT:
                doTimeout();
                break;
            default:
                break;
        }
    }
}
 
Example #27
Source File: PlayGames.java    From remixed-dungeon with GNU General Public License v3.0 5 votes vote down vote up
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
	if (requestCode != RC_SIGN_IN) {
		return false;
	}

	GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
	
	if (result.isSuccess()) {
		signedInAccount = result.getSignInAccount();
		onConnected();
	} else {

		Status status = result.getStatus();

		if(status.hasResolution()) {
			try {
				status.getResolution().send();
			} catch (PendingIntent.CanceledException e) {
				EventCollector.logException(e);
			}
			return true;
		}

		String message = status.getStatusMessage();
		if (message == null || message.isEmpty()) {
			message = status.toString();
		}
		new AlertDialog.Builder(Game.instance()).setMessage(message)
				.setNeutralButton(android.R.string.ok, null).show();
	}
	return true;

}
 
Example #28
Source File: MainActivity.java    From connectivity-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Publishes a message to nearby devices and updates the UI if the publication either fails or
 * TTLs.
 */
private void publish() {
    Log.i(TAG, "Publishing");
    PublishOptions options = new PublishOptions.Builder()
            .setStrategy(PUB_SUB_STRATEGY)
            .setCallback(new PublishCallback() {
                @Override
                public void onExpired() {
                    super.onExpired();
                    Log.i(TAG, "No longer publishing");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mPublishSwitch.setChecked(false);
                        }
                    });
                }
            }).build();

    Nearby.Messages.publish(mGoogleApiClient, mPubMessage, options)
            .setResultCallback(new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    if (status.isSuccess()) {
                        Log.i(TAG, "Published successfully.");
                    } else {
                        logAndShowSnackbar("Could not publish, status = " + status);
                        mPublishSwitch.setChecked(false);
                    }
                }
            });
}
 
Example #29
Source File: MainActivity.java    From nearby-beacons with MIT License 5 votes vote down vote up
@Override
public void onResult(@NonNull Status status) {
    //Validate if we were able to register for background scans
    if (status.isSuccess()) {
        Log.d(TAG, "Background Register Success!");
    } else {
        Log.w(TAG, "Background Register Error ("
                + status.getStatusCode() + "): "
                + status.getStatusMessage());
    }
}
 
Example #30
Source File: GeofencingRemoveSingleOnSubscribe.java    From RxGps with Apache License 2.0 5 votes vote down vote up
@Override
protected void onGoogleApiClientReady(GoogleApiClient apiClient, SingleEmitter<Status> emitter) {
    ResultCallback<Status> resultCallback = SingleResultCallBack.get(emitter);

    if (geofenceRequestIds != null) {
        setupLocationPendingResult(LocationServices.GeofencingApi.removeGeofences(apiClient, geofenceRequestIds), resultCallback);
    } else {
        setupLocationPendingResult(LocationServices.GeofencingApi.removeGeofences(apiClient, pendingIntent), resultCallback);
    }
}