public override Android.App.Dialog OnCreateDialog(Bundle bundle) { Bundle args = GetArguments(); return(GooglePlayServicesUtil.GetErrorDialog(args.GetInt(ARG_ERROR_CODE), GetActivity(), args.GetInt(ARG_REQUEST_CODE))); }
protected override Dialog OnCreateDialog(int id) { if (id != DIALOG_GET_GOOGLE_PLAY_SERVICES) { return(base.OnCreateDialog(id)); } int available = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this); if (available == CommonStatusCodes.Success) { return(null); } if (GooglePlayServicesUtil.IsUserRecoverableError(available)) { return(GooglePlayServicesUtil.GetErrorDialog( available, this, REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES, this)); } return(new AlertDialog.Builder(this) .SetMessage(Resource.String.plus_generic_error) .SetCancelable(true) .SetOnCancelListener(this) .Create()); }
private bool CheckPlayServices() { var context = Mvx.Resolve <IMvxAndroidCurrentTopActivity>().Activity; var resultCode = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(context); if (resultCode == ConnectionResult.Success) { return(true); } if (GooglePlayServicesUtil.IsUserRecoverableError(resultCode)) { GooglePlayServicesUtil.GetErrorDialog(resultCode, context, 9000); } else { if (Error != null) { Error(this, new NotificationErrorEventArgs { Message = "This device is not supported" }); } } return(false); }
public void OnConnectionFailed(ConnectionResult result) { if (result.HasResolution) { try { _googleAccountPopupOpened = true; if (_fromActivity) { _activity.StartIntentSenderForResult(result.Resolution.IntentSender, RequestCodeGoogleDriveRetryConnection, null, 0, 0, 0, null); } else { _fragment.StartIntentSenderForResult(result.Resolution.IntentSender, RequestCodeGoogleDriveRetryConnection, null, 0, 0, 0, null); } } catch (IntentSender.SendIntentException ex) { //Connected?.Invoke(this, success: false); } } else { var activity = _fromActivity ? _activity : _fragment.Activity; GooglePlayServicesUtil.GetErrorDialog(result.ErrorCode, activity, 0).Show(); } }
void BuildFitnessClient() { var clientConnectionCallback = new ClientConnectionCallback(); clientConnectionCallback.OnConnectedImpl = () => Subscribe(); // Create the Google API Client mClient = new GoogleApiClient.Builder(this) .AddApi(FitnessClass.RECORDING_API) .AddScope(new Scope(Scopes.FitnessActivityRead)) .AddConnectionCallbacks(clientConnectionCallback) .AddOnConnectionFailedListener((ConnectionResult result) => { Log.Info(TAG, "Connection failed. Cause: " + result.ToString()); if (!result.HasResolution) { // Show the localized error dialog GooglePlayServicesUtil.GetErrorDialog(result.ErrorCode, this, 0).Show(); return; } // The failure has a resolution. Resolve it. // Called typically when the app is not yet authorized, and an // authorization dialog is displayed to the user. if (!authInProgress) { try { Log.Info(TAG, "Attempting to resolve failed connection"); result.StartResolutionForResult(this, REQUEST_OAUTH); } catch (IntentSender.SendIntentException e) { Log.Error(TAG, "Exception while starting resolution activity", e); } } }).Build(); }
bool resolveConnectionFailure(Activity activity, Android.Gms.Common.Apis.GoogleApiClient client, ConnectionResult result, int requestCode, string fallbackErrorMessage) { if (result.HasResolution) { try { result.StartResolutionForResult(activity, requestCode); return(true); } catch (IntentSender.SendIntentException e) { // The intent was canceled before it was sent. Return to the default // state and attempt to connect to get an updated ConnectionResult. client.Connect(); return(false); } } else { // not resolvable... so show an error message int errorCode = result.ErrorCode; var dialog = GooglePlayServicesUtil.GetErrorDialog(errorCode, activity, requestCode); if (dialog != null) { dialog.Show(); } else { // no built-in dialog: show the fallback error message //ShowAlert (activity, fallbackErrorMessage); (new AlertDialog.Builder(activity)).SetMessage(fallbackErrorMessage) .SetNeutralButton(Android.Resource.String.Ok, delegate { }).Create().Show(); } return(false); } }
void BuildFitnessClient() { var clientConnectionCallback = new ClientConnectionCallback(); clientConnectionCallback.OnConnectedImpl = () => FindFitnessDataSources(); mClient = new GoogleApiClient.Builder(this) .AddApi(FitnessClass.SENSORS_API) .AddScope(new Scope(Scopes.FitnessLocationRead)) .AddConnectionCallbacks(clientConnectionCallback) .AddOnConnectionFailedListener((ConnectionResult result) => { Log.Info(TAG, "Connection failed. Cause: " + result); if (!result.HasResolution) { // Show the localized error dialog GooglePlayServicesUtil.GetErrorDialog(result.ErrorCode, this, 0).Show(); return; } if (!authInProgress) { try { Log.Info(TAG, "Attempting to resolve failed connection"); authInProgress = true; result.StartResolutionForResult(this, REQUEST_OAUTH); } catch (IntentSender.SendIntentException e) { Log.Error(TAG, "Exception while starting resolution activity", e); } } }).Build(); }
void ShowErrorDialog(ConnectionResult connectionResult) { int errorCode = connectionResult.ErrorCode; if (GooglePlayServicesUtil.IsUserRecoverableError(errorCode)) { var listener = new DialogInterfaceOnCancelListener(); listener.OnCancelImpl = (dialog) => { mShouldResolve = false; // UpdateUI(false); }; GooglePlayServicesUtil.GetErrorDialog(errorCode, this, RC_SIGN_IN, listener).Show(); } else { //var errorstring = string.Format(GetString(Resource.String.play_services_error_fmt), errorCode); //Toast.MakeText(this, errorstring, ToastLength.Short).Show(); mShouldResolve = false; //UpdateUI(false); } HandleResult(new GoogleLoginResult { IsSuccess = false, Message = connectionResult.ErrorMessage }); }
public void ProviderInstallerCheck(Context context) { try { // Checking if the ProviderInstaller is installed and updated ProviderInstaller.InstallIfNeeded(context); Toast.MakeText(context, "Provider installed and updated!", ToastLength.Long).Show(); } catch (GooglePlayServicesRepairableException e) { /* If the ProviderInstaller is installed but not updated * A popup asks the user to do a manual update of the Google Play Services */ #pragma warning disable CS0618 // Type or member is obsolete GooglePlayServicesUtil.ShowErrorNotification(e.ConnectionStatusCode, context); #pragma warning restore CS0618 // Type or member is obsolete Toast.MakeText(context, "Provider it outdated. Please update your Google Play Service", ToastLength.Long).Show(); } catch (GooglePlayServicesNotAvailableException e) { /* If the ProviderInstaller is not installed but not updated * A popup redirects the user to the Google Play Services page on the Google PlayStore * and let the user download them. */ #pragma warning disable CS0618 // Type or member is obsolete Dialog dialog = GooglePlayServicesUtil.GetErrorDialog(e.ErrorCode, this, REQUEST_GOOGLE_PLAY_SERVICES_DOWNLOAD); #pragma warning restore CS0618 // Type or member is obsolete dialog.SetCancelable(false); dialog.Show(); } }
// [END auth_oncreate_setup_ending] // [START auth_build_googleapiclient_beginning] /** * Build a {@link GoogleApiClient} that will authenticate the user and allow the application * to connect to Fitness APIs. The scopes included should match the scopes your app needs * (see documentation for details). Authentication will occasionally fail intentionally, * and in those cases, there will be a known resolution, which the OnConnectionFailedListener() * can address. Examples of this include the user never having signed in before, or having * multiple accounts on the device and needing to specify which account to use, etc. */ void buildFitnessClient() { // Create the Google API Client mClient = new GoogleApiClient.Builder(this) .AddApi(FitnessClass.SENSORS_API) .AddScope(new Scope(Scopes.FitnessLocationRead)) .AddConnectionCallbacks( bundle => { Log(TAG, "Connected!!!"); // Now you can make calls to the Fitness APIs. // Put application specific code here. // [END auth_build_googleapiclient_beginning] // What to do? Find some data sources! findFitnessDataSources(); // [START auth_build_googleapiclient_ending] }, i => { // If your connection to the sensor gets lost at some point, // you'll be able to determine the reason and react to it here. if (i == GoogleApiClient.ConnectionCallbacks.CauseNetworkLost) { Log(TAG, "Connection lost. Cause: Network Lost."); } else if (i == GoogleApiClient.ConnectionCallbacks.CauseServiceDisconnected) { Log(TAG, "Connection lost. Reason: Service Disconnected"); } }) .AddOnConnectionFailedListener( result => { Log(TAG, "Connection failed. Cause: " + result); if (!result.HasResolution) { // Show the localized error dialog GooglePlayServicesUtil.GetErrorDialog(result.ErrorCode, this, 0).Show(); return; } // The failure has a resolution. Resolve it. // Called typically when the app is not yet authorized, and an // authorization dialog is displayed to the user. if (!authInProgress) { try { Log(TAG, "Attempting to resolve failed connection"); authInProgress = true; result.StartResolutionForResult(this, REQUEST_OAUTH); } catch (IntentSender.SendIntentException e) { Log(TAG, "Exception while starting resolution activity: " + e); } } }) .Build(); }
async void BuildFitnessClient(Activity activity) { var clientConnectionCallback = new ClientConnectionCallback(); clientConnectionCallback.OnConnectedImpl = () => { /*DataSet dataSet = InsertFitnessData (); * * Log.Info (TAG, "Inserting the dataset in the History API"); * var insertStatus = (Statuses)FitnessClass.HistoryApi.InsertData (mClient, dataSet).Await (1, TimeUnit.Minutes); * * if (!insertStatus.IsSuccess) { * Log.Info (TAG, "There was a problem inserting the dataset."); * return; * } * * Log.Info (TAG, "Data insert was successful!"); * * DataReadRequest readRequest = QueryFitnessData (); * * var dataReadResult = await FitnessClass.HistoryApi.ReadDataAsync (mClient, readRequest); * * PrintData (dataReadResult);*/ RefreshHealthStateData(); }; // Create the Google API Client mClient = new GoogleApiClient.Builder(activity) .AddApi(FitnessClass.HISTORY_API) .AddScope(new Scope(Scopes.FitnessActivityReadWrite)) .AddConnectionCallbacks(clientConnectionCallback) .AddOnConnectionFailedListener(result => { Log.Info(TAG, "Connection failed. Cause: " + result); if (!result.HasResolution) { // Show the localized error dialog GooglePlayServicesUtil.GetErrorDialog(result.ErrorCode, activity, 0).Show(); return; } // The failure has a resolution. Resolve it. // Called typically when the app is not yet authorized, and an // authorization dialog is displayed to the user. if (!authInProgress) { try { Log.Info(TAG, "Attempting to resolve failed connection"); authInProgress = true; result.StartResolutionForResult(activity, REQUEST_OAUTH); } catch (IntentSender.SendIntentException e) { Log.Error(TAG, "Exception while starting resolution activity", e); } } }).Build(); }
public Dialog ErrorDialog(int errorCode) { Dialog errorDialog = GooglePlayServicesUtil.GetErrorDialog(errorCode, activity, RC_UNUSED, null); if (errorDialog != null) { return(errorDialog); } return((new AlertDialog.Builder(activity)) .SetMessage(unknownErrorMessage + " " + errorCode) .SetNeutralButton(Android.Resource.String.Ok, (EventHandler <DialogClickEventArgs>)null) .Create()); }
public void OnConnectionFailed(ConnectionResult result) { if (result.HasResolution) { try { result.StartResolutionForResult(this, 101); } catch (IntentSender.SendIntentException ex) { // Unable to resolve, message user appropriately } } else { GooglePlayServicesUtil.GetErrorDialog(result.ErrorCode, this, 0).Show(); } }
bool CheckGooglePlayServices () { var result = GooglePlayServicesUtil.IsGooglePlayServicesAvailable (this); if (result == ConnectionResult.Success) return true; var dialog = GooglePlayServicesUtil.GetErrorDialog (result, this, ConnectionFailureResolutionRequest); if (dialog != null) { var errorDialog = new ErrorDialogFragment { Dialog = dialog }; errorDialog.Show (SupportFragmentManager, "Google Services Updates"); return false; } Finish (); return false; }
void CheckOldGooglePlayServices(Activity activity) { var isAvailable = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(activity); if (isAvailable != ConnectionResult.Success) { if (GooglePlayServicesUtil.IsUserRecoverableError(isAvailable)) { var dialog = GooglePlayServicesUtil.GetErrorDialog(isAvailable, activity, SIGN_IN_REQUEST_CODE); dialog.Show(); throw new Exception(GooglePlayServicesUtil.GetErrorString(isAvailable)); } else { throw new Exception("This device is not Supported"); } } }
/** * Show a {@link android.app.Dialog} with the correct message for a connection error. * @param activity the Activity in which the Dialog should be displayed. * @param requestCode the request code from onActivityResult. * @param actResp the response code from onActivityResult. * @param errorDescription the resource id of a String for a generic error message. */ public static void ShowActivityResultError(Activity activity, int requestCode, int actResp, int errorDescription) { if (activity == null) { Log.Error("BaseGameUtils", "*** No Activity. Can't show failure dialog!"); return; } Dialog errorDialog; switch (actResp) { case GamesActivityResultCodes.ResultAppMisconfigured: errorDialog = MakeSimpleDialog(activity, activity.GetString(Resource.String.app_misconfigured)); break; case GamesActivityResultCodes.ResultSignInFailed: errorDialog = MakeSimpleDialog(activity, activity.GetString(Resource.String.sign_in_failed)); break; case GamesActivityResultCodes.ResultLicenseFailed: errorDialog = MakeSimpleDialog(activity, activity.GetString(Resource.String.license_failed)); break; default: // No meaningful Activity response code, so generate default Google // Play services dialog int errorCode = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(activity); errorDialog = GooglePlayServicesUtil.GetErrorDialog(errorCode, activity, requestCode, null); if (errorDialog == null) { // get fallback dialog Log.Error("BaseGamesUtils", "No standard error dialog available. Making fallback dialog."); errorDialog = MakeSimpleDialog(activity, activity.GetString(errorDescription)); } break; } errorDialog.Show(); }
private bool CheckPlayServices() { int resultCode = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.Success) { if (GooglePlayServicesUtil.IsUserRecoverableError(resultCode)) { GooglePlayServicesUtil.GetErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).Show(); } else { Log.Info(TAG, "This device is not supported."); Finish(); } return(false); } return(true); }
public static bool CheckPlayServices(Activity context) { int result = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(context); if (result != ConnectionResult.Success) { if (GooglePlayServicesUtil.IsUserRecoverableError(result)) { GooglePlayServicesUtil.GetErrorDialog(result, context, PLAY_SERVICE_RESOLUTION_REQ).Show(); } else { Log.Debug("GetMapAsync", "Google Play Services is not supported on this device"); context.Finish(); } return(false); } return(true); //we're good }
private bool CheckPlayServices() { int resultCode = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.Success) { if (GooglePlayServicesUtil.IsUserRecoverableError(resultCode)) { GooglePlayServicesUtil.GetErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).Show(); } else { Toast.MakeText(ApplicationContext, "This device does not support Google Play Services", ToastLength.Long).Show(); Finish(); } return(false); } return(true); }
private bool TestIfGooglePlayServicesIsInstalled() { var queryResult = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this); if (queryResult == ConnectionResult.Success) { Log.Info("AppCompatAndMaps", "Google Play Services is installed on this device."); return(true); } if (GooglePlayServicesUtil.IsUserRecoverableError(queryResult)) { var errorString = GooglePlayServicesUtil.GetErrorString(queryResult); Log.Error("AppCompatAndMaps", "There is a problem with Google Play Services on this device: {0} - {1}", queryResult, errorString); var errorDialog = GooglePlayServicesUtil.GetErrorDialog(queryResult, this, InstallGooglePlayServicesId); errorDialog.Show(); } return(false); }
/** * Helper to try to resolve a user recoverable error (i.e. the user has an out of date version * of Google Play Services installed), via an error dialog provided by * {@link GooglePlayServicesUtil#getErrorDialog(int, Activity, int, OnCancelListener)}. If an, * error is not user recoverable then the error will be handled in {@link #handleError(int)}. */ protected void resolveUnsuccessfulConnectionResult() { // Additional user input is needed if (mConnectionResult.HasResolution) { try { mConnectionResult.StartResolutionForResult(Activity, REQUEST_CODE_RESOLVE_ERR); } catch (IntentSender.SendIntentException) { reconnect(); } } else { int errorCode = mConnectionResult.ErrorCode; if (GooglePlayServicesUtil.IsUserRecoverableError(errorCode)) { var dialog = GooglePlayServicesUtil.GetErrorDialog(errorCode, Activity, REQUEST_CODE_RESOLVE_ERR, this); // the dialog will either be dismissed, which will invoke the OnCancelListener, or // the dialog will be addressed, which will result in a callback to // OnActivityResult() dialog.Show(); } else { switch (errorCode) { case ConnectionResult.InternalError: case ConnectionResult.NetworkError: reconnect(); break; default: handleError(errorCode); break; } } } mConnectionResult = null; }
void ShowErrorDialog(ConnectionResult connectionResult) { int errorCode = connectionResult.ErrorCode; if (GooglePlayServicesUtil.IsUserRecoverableError(errorCode)) { var listener = new DialogInterfaceOnCancelListener(); listener.OnCancelImpl = (dialog) => { mShouldResolve = false; }; GooglePlayServicesUtil.GetErrorDialog(errorCode, this, RC_SIGN_IN, listener).Show(); } else { mShouldResolve = false; } HandleResult(new GoogleLoginResult { IsSuccess = false, Message = connectionResult.ErrorMessage }); }
private bool TestIfGooglePlayServicesIsInstalled() { int queryResult = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this); if (queryResult == ConnectionResult.Success) { Log.Info(Tag, "Google Play Services is installed on this device."); return(true); } if (GooglePlayServicesUtil.IsUserRecoverableError(queryResult)) { string errorString = GooglePlayServicesUtil.GetErrorString(queryResult); Log.Error(Tag, "There is a problem with Google Play Services on this device: {0} - {1}", queryResult, errorString); Dialog errorDialog = GooglePlayServicesUtil.GetErrorDialog(queryResult, this, InstallGooglePlayServicesId); ErrorDialogFragment dialogFrag = new ErrorDialogFragment(errorDialog); dialogFrag.Show(FragmentManager, "GooglePlayServicesDialog"); } return(false); }
protected void GCMInit() { try { PackageInfo pInfo = this.Activity.PackageManager.GetPackageInfo(this.Activity.PackageName, 0); var shared = this.Activity.GetSharedPreferences(); var version = shared.GetInt(GetString(Resource.String.shared_preferences_version), 0); var temp = shared.GetString(GetString(Resource.String.shared_preferences_gcm_handle), null); if (temp != null) { GcmClient.UnRegister(Activity); } // If already registered for GCM, or if not connected to the internet proceed to login if (isNetworkAvailable()) { // Check for Google GCM int errorCode = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this.Activity); if (errorCode == ConnectionResult.Success) { GcmClient.Register(this.Activity, GcmBroadcastReceiver.SENDER_IDS); Insight.Track("GcmClient.Register"); } else { const int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; Android.App.Dialog dialog = GooglePlayServicesUtil.GetErrorDialog(errorCode, this.Activity, PLAY_SERVICES_RESOLUTION_REQUEST); dialog.DismissEvent += delegate { this.Activity.Finish(); }; dialog.Show(); } } } catch (Exception e) { Insight.Report(e); } }
public void GetHealthPermissionAsync(Action <bool> completion) { AuthorizationCallBack = completion; mGoogleApiClient = new GoogleApiClient.Builder(Forms.Context) .AddConnectionCallbacks(this) .AddApi(FitnessClass.HISTORY_API) .AddScope(new Scope(Scopes.FitnessActivityReadWrite)) .AddScope(new Scope(Scopes.FitnessLocationRead)) .AddOnConnectionFailedListener(result => { Log.Info("apiClient", "Connection failed. Cause: " + result); if (!result.HasResolution) { // Show the localized error dialog GooglePlayServicesUtil.GetErrorDialog(result.ErrorCode, (Activity)Forms.Context, 0).Show(); return; } // The failure has a resolution. Resolve it. // Called typically when the app is not yet authorized, and an // authorization dialog is displayed to the user. if (!authInProgress) { try { Log.Info("apiClient", "Attempting to resolve failed connection"); authInProgress = true; result.StartResolutionForResult((Activity)Forms.Context, REQUEST_OAUTH); } catch (Exception e) { Log.Error("apiClient", "Exception while starting resolution activity", e); } } }).Build(); //mGoogleApiClient.Connect(); ((MainActivity)Forms.Context).ActivityResult += HandleActivityResult; mGoogleApiClient.Connect(); }
void ShowErrorDialog(ConnectionResult connectionResult) { int errorCode = connectionResult.ErrorCode; if (GooglePlayServicesUtil.IsUserRecoverableError(errorCode)) { var listener = new DialogInterfaceOnCancelListener(); listener.OnCancelImpl = (dialog) => { mShouldResolve = false; UpdateUI(false); }; GooglePlayServicesUtil.GetErrorDialog(errorCode, this, RC_SIGN_IN, listener).Show(); } else { var errorstring = string.Format("{0}", errorCode); Toast.MakeText(this, errorstring, ToastLength.Short).Show(); mShouldResolve = false; UpdateUI(false); } }
/** * Resolve a connection failure from * {@link com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener#onConnectionFailed(com.google.android.gms.common.ConnectionResult)} * * @param activity the Activity trying to resolve the connection failure. * @param client the GoogleAPIClient instance of the Activity. * @param result the ConnectionResult received by the Activity. * @param requestCode a request code which the calling Activity can use to identify the result * of this resolution in onActivityResult. * @param fallbackErrorMessage a generic error message to display if the failure cannot be resolved. * @return true if the connection failure is resolved, false otherwise. */ public static bool ResolveConnectionFailure(Activity activity, GoogleApiClient client, ConnectionResult result, int requestCode, string fallbackErrorMessage) { if (result.HasResolution) { try { result.StartResolutionForResult(activity, requestCode); return(true); } catch (IntentSender.SendIntentException e) { // The intent was canceled before it was sent. Return to the default // state and attempt to connect to get an updated ConnectionResult. client.Connect(); return(false); } } else { // not resolvable... so show an error message int errorCode = result.ErrorCode; Dialog dialog = GooglePlayServicesUtil.GetErrorDialog(errorCode, activity, requestCode); if (dialog != null) { dialog.Show(); } else { // no built-in dialog: show the fallback error message ShowAlert(activity, fallbackErrorMessage); } return(false); } }
private async void StartAuth() { if (IsAuthenticating) { return; } IsAuthenticating = true; LoginActivity activity; try { var log = ServiceContainer.Resolve <Logger> (); var authManager = ServiceContainer.Resolve <AuthManager> (); var ctx = Activity; // Workaround for Android linker bug which forgets to register JNI types Java.Interop.TypeManager.RegisterType("com/google/android/gms/auth/GoogleAuthException", typeof(GoogleAuthException)); Java.Interop.TypeManager.RegisterType("com/google/android/gms/auth/GooglePlayServicesAvailabilityException", typeof(GooglePlayServicesAvailabilityException)); Java.Interop.TypeManager.RegisterType("com/google/android/gms/auth/UserRecoverableAuthException", typeof(UserRecoverableAuthException)); Java.Interop.TypeManager.RegisterType("com/google/android/gms/auth/UserRecoverableNotifiedException", typeof(UserRecoverableNotifiedException)); String token = null; try { token = await Task.Factory.StartNew(() => GoogleAuthUtil.GetToken(ctx, Email, GoogleOAuthScope)); } catch (GooglePlayServicesAvailabilityException exc) { var dia = GooglePlayServicesUtil.GetErrorDialog( exc.ConnectionStatusCode, ctx, GoogleAuthRequestCode); dia.Show(); } catch (UserRecoverableAuthException exc) { StartActivityForResult(exc.Intent, GoogleAuthRequestCode); } catch (Java.IO.IOException exc) { // Connectivity error.. nothing to do really? log.Info(Tag, exc, "Failed to login with Google due to network issues."); } catch (Exception exc) { log.Error(Tag, exc, "Failed to get access token for '{0}'.", Email); } // Failed to get token if (token == null) { return; } activity = Activity as LoginActivity; if (activity != null && activity.CurrentMode == Mode.Signup) { // Signup with Google var success = await authManager.SignupWithGoogle(token); if (!success) { GoogleAuthUtil.InvalidateToken(ctx, token); new SignupFailedDialogFragment().Show(FragmentManager, "invalid_credentials_dialog"); } } else { // Authenticate client var success = await authManager.AuthenticateWithGoogle(token); if (!success) { GoogleAuthUtil.InvalidateToken(ctx, token); new NoAccountDialogFragment().Show(FragmentManager, "invalid_credentials_dialog"); } } } finally { IsAuthenticating = false; } // Clean up self: if (Activity != null) { FragmentManager.BeginTransaction() .Remove(this) .Commit(); } // Try to make the activity recheck auth status activity = Activity as LoginActivity; if (activity != null) { activity.StartAuthActivity(); } }
void BuildFitnessClient() { var clientConnectionCallback = new ClientConnectionCallback(); clientConnectionCallback.OnConnectedImpl = () => { SessionInsertRequest insertRequest = InsertFitnessSession(); // [START insert_session] // Then, invoke the Sessions API to insert the session and await the result, // which is possible here because of the AsyncTask. Always include a timeout when // calling await() to avoid hanging that can occur from the service being shutdown // because of low memory or other conditions. Log.Info(TAG, "Inserting the session in the History API"); var insertStatus = (Statuses)FitnessClass.SessionsApi.InsertSession(mClient, insertRequest).Await(1, TimeUnit.Minutes); // Before querying the session, check to see if the insertion succeeded. if (!insertStatus.IsSuccess) { Log.Info(TAG, "There was a problem inserting the session: " + insertStatus.StatusMessage); return; } // At this point, the session has been inserted and can be read. Log.Info(TAG, "Session insert was successful!"); // [END insert_session] // Begin by creating the query. var readRequest = ReadFitnessSession(); // [START read_session] // Invoke the Sessions API to fetch the session with the query and wait for the result // of the read request. var sessionReadResult = (SessionReadResult)FitnessClass.SessionsApi.ReadSession(mClient, readRequest).Await(1, TimeUnit.Minutes); // Get a list of the sessions that match the criteria to check the result. Log.Info(TAG, "Session read was successful. Number of returned sessions is: " + sessionReadResult.Sessions.Count); foreach (Session session in sessionReadResult.Sessions) { // Process the session DumpSession(session); // Process the data sets for this session IList <DataSet> dataSets = sessionReadResult.GetDataSet(session); foreach (DataSet dataSet in dataSets) { DumpDataSet(dataSet); } } }; // Create the Google API Client mClient = new GoogleApiClientBuilder(this) .AddApi(FitnessClass.HISTORY_API) .AddScope(new Scope(Scopes.FitnessActivityReadWrite)) .AddConnectionCallbacks(clientConnectionCallback) .AddOnConnectionFailedListener(result => { Log.Info(TAG, "Connection failed. Cause: " + result); if (!result.HasResolution) { // Show the localized error dialog GooglePlayServicesUtil.GetErrorDialog(result.ErrorCode, this, 0).Show(); return; } // The failure has a resolution. Resolve it. // Called typically when the app is not yet authorized, and an // authorization dialog is displayed to the user. if (!authInProgress) { try { Log.Info(TAG, "Attempting to resolve failed connection"); authInProgress = true; result.StartResolutionForResult(this, REQUEST_OAUTH); } catch (IntentSender.SendIntentException e) { Log.Error(TAG, "Exception while starting resolution activity", e); } } }).Build(); }
private async Task StartAuthAsync() { if (IsAuthenticating) { return; } IsAuthenticating = true; try { var log = ServiceContainer.Resolve <ILogger> (); var authManager = ServiceContainer.Resolve <AuthManager> (); var ctx = Activity; // No point in trying to reauth when old authentication is still running. if (authManager.IsAuthenticating) { return; } // Workaround for Android linker bug which forgets to register JNI types Java.Interop.TypeManager.RegisterType("com/google/android/gms/auth/GoogleAuthException", typeof(GoogleAuthException)); Java.Interop.TypeManager.RegisterType("com/google/android/gms/auth/GooglePlayServicesAvailabilityException", typeof(GooglePlayServicesAvailabilityException)); Java.Interop.TypeManager.RegisterType("com/google/android/gms/auth/UserRecoverableAuthException", typeof(UserRecoverableAuthException)); Java.Interop.TypeManager.RegisterType("com/google/android/gms/auth/UserRecoverableNotifiedException", typeof(UserRecoverableNotifiedException)); String token = null; try { token = await Task.Factory.StartNew(() => GoogleAuthUtil.GetToken(ctx, Email, GoogleOAuthScope)); } catch (GooglePlayServicesAvailabilityException exc) { var dia = GooglePlayServicesUtil.GetErrorDialog( exc.ConnectionStatusCode, ctx, GoogleAuthRequestCode); dia.Show(); } catch (UserRecoverableAuthException exc) { StartActivityForResult(exc.Intent, GoogleAuthRequestCode); } catch (Java.IO.IOException exc) { // Connectivity error.. nothing to do really? log.Info(LogTag, exc, "Failed to login with Google due to network issues."); } catch (Exception exc) { log.Error(LogTag, exc, "Failed to get access token for '{0}'.", Email); } // Failed to get token if (token == null) { return; } try { var authRes = await viewModel.TrySignupGoogleAsync(token); if (authRes != AuthResult.Success) { ClearGoogleToken(ctx, token); var dia = new ErrorDialogFragment(authRes); dia.Show(FragmentManager, "auth_result_dialog"); } } catch (InvalidOperationException ex) { log.Info(LogTag, ex, "Failed to authenticate user with Google login."); } } finally { IsAuthenticating = false; } // Clean up self: if (Activity != null) { FragmentManager.BeginTransaction() .Remove(this) .Commit(); } }