Beispiel #1
0
		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;
		}
Beispiel #2
0
        protected override void OnCreate(Bundle savedState)
        {
            base.OnCreate(savedState);

            var scroll = new ScrollView(this);

            var license = new TextView(this);

            license.Text = GooglePlayServicesUtil.GetOpenSourceSoftwareLicenseInfo(this);
            scroll.AddView(license);

            SetContentView(scroll);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Honeycomb)
            {
                ActionBar.SetDisplayHomeAsUpEnabled(true);
            }
        }
Beispiel #3
0
            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");
                    }
                }
            }
Beispiel #4
0
 protected override void OnCreate(Bundle savedInstance)
 {
     base.OnCreate(savedInstance);
     // Calling this method triggers a validation error.
     Android.Content.Context context = ApplicationContext;
     if (null != context)
     {
         int result = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(context);
         if (ConnectionResult.SUCCESS != result)
         {
             switch (result)
             {
             case ConnectionResult.SERVICE_MISSING:
                 break;
             }
         }
     }
 }
Beispiel #5
0
        /**
         * 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();
        }
Beispiel #6
0
        protected override void OnCreate(Android.OS.Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.legal_info);

            var    legalInfoTextView             = FindViewById <TextView> (Resource.Id.legal_info);
            string openSourceSoftwareLicenseInfo =
                GooglePlayServicesUtil.GetOpenSourceSoftwareLicenseInfo(this);

            if (openSourceSoftwareLicenseInfo != null)
            {
                legalInfoTextView.Text = openSourceSoftwareLicenseInfo;
            }
            else
            {
                legalInfoTextView.SetText(Resource.String.play_services_not_installed);
            }
        }
Beispiel #7
0
        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);
        }
Beispiel #8
0
        bool IsGooglePlayServicesInstalled()
        {
            int queryResult = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this);

            if (queryResult == ConnectionResult.Success)
            {
                Log.Info("MainActivity", "Google Play Services is installed on this device.");
                return(true);
            }

            if (GooglePlayServicesUtil.IsUserRecoverableError(queryResult))
            {
                string errorString = GooglePlayServicesUtil.GetErrorString(queryResult);
                Log.Error("ManActivity", "There is a problem with Google Play Services on this device: {0} - {1}", queryResult, errorString);

                // Show error dialog to let user debug google play services
            }
            return(false);
        }
        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);
        }
        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 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);
        }
Beispiel #12
0
 public void OnConnectionFailed(ConnectionResult result)
 {
     Debug.WriteLine("Google API connection failed!");
     if (result.HasResolution)
     {
         try
         {
             Debug.WriteLine("Google API start asking");
             result.StartResolutionForResult(MainActivity.Current, RESULT_CODE);
         }
         catch (IntentSender.SendIntentException e)
         {
             // Unable to resolve, message user appropriately
         }
     }
     else
     {
         GooglePlayServicesUtil.ShowErrorDialogFragment(result.ErrorCode, MainActivity.Current, 0);
     }
 }
Beispiel #13
0
        protected override void OnResume()
        {
            base.OnResume();
            if (!firstCreate)
            {
                circlesFragment.LoadData(this);
            }
            var avail = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this);

            if (avail == ConnectionResult.Success)
            {
                if (prefs.Enabled)
                {
                    SetTrackingEnabled(true);
                }
                return;
            }
            delayOnBoarding = true;
            GooglePlayServicesUtil.ShowErrorDialogFragment(avail, this, GooglePlayServiceResult, this);
        }
        /**
         * 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
            });
        }
Beispiel #16
0
        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);
            }
        }
Beispiel #18
0
        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);
            }
        }
        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();
        }
        /// <summary>
        /// Retourne vrai si les services google play sont disponnible sur le device exécutant l'appli
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static bool IsPlayServicesAvailable(Context context)
        {
            int resultCode = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(context);

            if (resultCode != ConnectionResult.Success)
            {
                if (GooglePlayServicesUtil.IsUserRecoverableError(resultCode))
                {
                    Console.WriteLine(GooglePlayServicesUtil.GetErrorString(resultCode));
                }
                else
                {
                    Console.WriteLine("Sorry, this device is not supported");
                }
                return(false);
            }
            else
            {
                Console.WriteLine("Google Play Services is available");
                return(true);
            }
        }
Beispiel #21
0
        protected override Dialog OnCreateDialog(int id)
        {
            if (id != DIALOG_GET_GOOGLE_PLAY_SERVICES)
            {
                return(base.OnCreateDialog(id));
            }

            var available = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this);

            if (available == ConnectionResult.Success)
            {
                return(null);
            }
            if (GooglePlayServicesUtil.IsUserRecoverableError(available))
            {
                return(GooglePlayServicesUtil.GetErrorDialog(
                           available, this, REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES));
            }
            return(new AlertDialog.Builder(this)
                   .SetMessage(Resource.String.plus_generic_error)
                   .SetCancelable(true)
                   .Create());
        }
Beispiel #22
0
        public bool IsPlayServicesAvailable()
        {
            int resultCode = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this);

            if (resultCode != ConnectionResult.Success)
            {
                if (GooglePlayServicesUtil.IsUserRecoverableError(resultCode))
                {
                    txtmsg.Text = GooglePlayServicesUtil.GetErrorString(resultCode);
                }
                else
                {
                    Toast.MakeText(this, "Sorry, this device is not supported", ToastLength.Short).Show();
                    Finish();
                }
                return(false);
            }
            else
            {
                Toast.MakeText(this, "Google Play Services is available.", ToastLength.Short).Show();
                return(true);
            }
        }
Beispiel #23
0
 /**
  * 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);
     }
 }
        void BuildFitnessClient()
        {
            var clientConnectionCallback = new ClientConnectionCallback();

            clientConnectionCallback.OnConnectedImpl = Subscribe;
            // Create the Google API Client
            mClient = new GoogleApiClientBuilder(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");
                        authInProgress = true;
                        result.StartResolutionForResult(this,
                                                        REQUEST_OAUTH);
                    } catch (IntentSender.SendIntentException e) {
                        Log.Error(TAG,
                                  "Exception while starting resolution activity", e);
                    }
                }
            })
                      .Build();
        }
Beispiel #25
0
        public bool IsPlayServicesAvailable()
        {
            int resultCode = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this);
            var left       = FindViewById <TextView> (Resource.Id.Left);

            if (resultCode != ConnectionResult.Success)
            {
                if (GooglePlayServicesUtil.IsUserRecoverableError(resultCode))
                {
                    left.Text = GooglePlayServicesUtil.GetErrorString(resultCode);
                }
                else
                {
                    left.Text = "Sorry, this device is not supported";
                    Finish();
                }
                return(false);
            }
            else
            {
                left.Text = "Google Play Services is available.";
                return(true);
            }
        }
        /// <summary>
        /// Attempt to Sign in to Google Play
        /// </summary>
        public void SignIn()
        {
            this.signingin = true;

            if (this.client == null)
            {
                this.CreateClient();
            }

            if (this.client.IsConnected ||
                this.client.IsConnecting)
            {
                return;
            }

            var result = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(activity);

            if (result != ConnectionResult.Success)
            {
                return;
            }

            this.Start();
        }
Beispiel #27
0
            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();
        }
Beispiel #29
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            try
            {
                Task <SmartBoxCity.Activity.Driver.TaskStatus> result = GetParameters();

                if (result.Result == Driver.TaskStatus.OK)
                {
                    var view = inflater.Inflate(Resource.Layout.activity_map, container, false);

                    txtFrom     = view.FindViewById <TextView>(Resource.Id.MapTextFrom);
                    txtTo       = view.FindViewById <TextView>(Resource.Id.MapTextTo);
                    Weight      = view.FindViewById <TextView>(Resource.Id.MapTextWeight);
                    LenhWidHeig = view.FindViewById <TextView>(Resource.Id.MapTextLenhWidHeig);

                    txtFrom.Text     = fromString;
                    txtTo.Text       = toString;
                    Weight.Text      = weightString;
                    LenhWidHeig.Text = lenhwidheigString;

                    var layout = view.FindViewById <SlidingUpPanelLayout>(Resource.Id.sliding_client_layout);
                    view.FindViewById <TextView>(Resource.Id.txt_info_order_new).MovementMethod = new LinkMovementMethod();



                    if (result.Result == SmartBoxCity.Activity.Driver.TaskStatus.OK)
                    {
                        layout.AnchorPoint     = 0.3f;
                        layout.PanelExpanded  += (s, e) => Log.Info(Tag, "PanelExpanded");
                        layout.PanelCollapsed += (s, e) => Log.Info(Tag, "PanelCollapsed");
                        layout.PanelAnchored  += (s, e) => Log.Info(Tag, "PanelAnchored");
                        layout.PanelSlide     += (s, e) =>
                        {
                            if (e.SlideOffset < 0.2)
                            {
                                //if (SupportActionBar.IsShowing)
                                //    SupportActionBar.Hide();
                            }
                            else
                            {
                                //if (!SupportActionBar.IsShowing)
                                //    SupportActionBar.Show();
                            }
                        };

                        var actionBarHidden = savedInstanceState != null &&
                                              savedInstanceState.GetBoolean(SavedStateActionBarHidden, false);
                        //if (actionBarHidden)
                        //    SupportActionBar.Hide();

                        MapsInitializer.Initialize(Activity);
                        mMapView = view.FindViewById <MapView>(Resource.Id.FragmentMapUser);

                        switch (GooglePlayServicesUtil.IsGooglePlayServicesAvailable(Activity))
                        {
                        case ConnectionResult.Success:
                            Toast.MakeText(Activity, "SUCCESS", ToastLength.Long).Show();
                            mMapView.OnCreate(savedInstanceState);
                            mMapView.GetMapAsync(this);
                            break;

                        case ConnectionResult.ServiceMissing:
                            Toast.MakeText(Activity, "ServiceMissing", ToastLength.Long).Show();
                            break;

                        case ConnectionResult.ServiceVersionUpdateRequired:
                            Toast.MakeText(Activity, "Update", ToastLength.Long).Show();
                            break;

                        default:
                            Toast.MakeText(Activity, GooglePlayServicesUtil.IsGooglePlayServicesAvailable(Activity), ToastLength.Long).Show();
                            break;
                        }
                    }

                    return(view);
                }
                else
                {
                    var view      = inflater.Inflate(Resource.Layout.activity_errors_handling, container, false);
                    var txt_error = view.FindViewById <TextView>(Resource.Id.TextOfError);
                    txt_error.Text = "Что-то пошло не так. Перезапустите страницу или обратитесь в центр поддержки!\nПричина: " + error_message;
                    return(view);
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(Activity, ex.Message, ToastLength.Long);
                var view      = inflater.Inflate(Resource.Layout.activity_errors_handling, container, false);
                var txt_error = view.FindViewById <TextView>(Resource.Id.TextOfError);
                txt_error.Text = "Что-то пошло не так. Перезапустите страницу или обратитесь в центр поддержки!\nПричина: " + ex.Message;
                return(view);
            }
        }
Beispiel #30
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.multi_moment_activity);

            var options = new PlusClass.PlusOptions.Builder().AddActivityTypes(MomentUtil.ACTIONS).Build();

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                               .AddConnectionCallbacks(this)
                               .AddOnConnectionFailedListener(this)
                               .AddApi(PlusClass.API, options)
                               .AddScope(PlusClass.ScopePlusLogin)
                               .Build();

            mListAdapter = new ArrayAdapter <string>(
                this, Android.Resource.Layout.SimpleListItem1, MomentUtil.MOMENT_LIST);
            mMomentListView            = FindViewById <ListView>(Resource.Id.moment_list);
            mMomentListView.ItemClick += (sender, e) => {
                if (mGoogleApiClient.IsConnected)
                {
                    var textView   = e.View as TextView;
                    var momentType = textView.Text;
                    var targetUrl  = MomentUtil.MOMENT_TYPES[momentType];

                    var target = new ItemScopeBuilder().SetUrl(targetUrl).Build();

                    var momentBuilder = new MomentBuilder();
                    momentBuilder.SetType("http://schemas.google.com/" + momentType);
                    momentBuilder.SetTarget(target);

                    var result = MomentUtil.GetResultFor(momentType);
                    if (result != null)
                    {
                        momentBuilder.SetResult(result);
                    }

                    PlusClass.MomentsApi.Write(mGoogleApiClient, momentBuilder.Build()).SetResultCallback <Statuses> (status =>
                    {
                        switch (status.StatusCode)
                        {
                        case CommonStatusCodes.Success:
                            Toast.MakeText(this, GetString(Resource.String.plus_write_moment_status_success), ToastLength.Short).Show();
                            break;

                        case CommonStatusCodes.SuccessCache:
                            Toast.MakeText(this, GetString(Resource.String.plus_write_moment_status_cached), ToastLength.Short).Show();
                            break;

                        case CommonStatusCodes.SignInRequired:
                            Toast.MakeText(this, GetString(Resource.String.plus_write_moment_status_auth_error), ToastLength.Short).Show();
                            mGoogleApiClient.Disconnect();
                            mGoogleApiClient.Connect();
                            break;

                        default:
                            Toast.MakeText(this, GetString(Resource.String.plus_write_moment_status_error),
                                           ToastLength.Short).Show();
                            Console.WriteLine("Error when writing moments: " + status);
                            break;
                        }
                    });
                }
            };

            mResolvingError = savedInstanceState != null &&
                              savedInstanceState.GetBoolean(STATE_RESOLVING_ERROR, false);

            var available = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this);

            if (available != CommonStatusCodes.Success)
            {
                ShowDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES);
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Honeycomb)
            {
                ActionBar.SetDisplayHomeAsUpEnabled(true);
            }
        }