Exemplo n.º 1
0
        protected override void OnPause()
        {
            base.OnPause();

            Log.Debug("OnPause", "OnPause called, stopping location updates");

            if (locClient.IsConnected)
            {
                // stop location updates, passing in the LocationListener
                LocationServices.FusedLocationApi.RemoveLocationUpdates(locClient, this);

                locClient.Disconnect();
            }
        }
Exemplo n.º 2
0
        protected override void OnHandleIntent(Intent intent)
        {
            google_api_client.BlockingConnect(TIME_OUT_MS, TimeUnit.Milliseconds);
            Android.Net.Uri dataItemUri = intent.Data;
            if (!google_api_client.IsConnected)
            {
                Log.Error(TAG, "Failed to update data item " + dataItemUri +
                          " because client is disconnected from Google Play Services");
                return;
            }
            var dataItemResult = WearableClass.DataApi.GetDataItem(
                google_api_client, dataItemUri).Await().JavaCast <IDataApiDataItemResult> ();

            var putDataMapRequest = PutDataMapRequest.CreateFromDataMapItem(
                DataMapItem.FromDataItem(dataItemResult.DataItem));
            var dataMap = putDataMapRequest.DataMap;

            //update quiz status variables
            int  questionIndex       = intent.GetIntExtra(EXTRA_QUESTION_INDEX, -1);
            bool chosenAnswerCorrect = intent.GetBooleanExtra(EXTRA_QUESTION_CORRECT, false);

            dataMap.PutInt(Constants.QUESTION_INDEX, questionIndex);
            dataMap.PutBoolean(Constants.CHOSEN_ANSWER_CORRECT, chosenAnswerCorrect);
            dataMap.PutBoolean(Constants.QUESTION_WAS_ANSWERED, true);
            PutDataRequest request = putDataMapRequest.AsPutDataRequest();

            WearableClass.DataApi.PutDataItem(google_api_client, request).Await();

            //remove this question notification
            ((NotificationManager)GetSystemService(NotificationService)).Cancel(questionIndex);
            google_api_client.Disconnect();
        }
Exemplo n.º 3
0
            public override void OnVisibilityChanged(bool visible)
            {
                base.OnVisibilityChanged(visible);
                if (Log.IsLoggable(Tag, LogPriority.Debug))
                {
                    Log.Debug(Tag, "OnVisibilityChanged: " + visible);
                }
                if (visible)
                {
                    googleApiClient.Connect();
                    RegisterTimezoneReceiver();
                }
                else
                {
                    UnregisterTimezoneReceiver();

                    if (googleApiClient != null && googleApiClient.IsConnected)
                    {
                        WearableClass.DataApi.RemoveListener(googleApiClient, this);
                        googleApiClient.Disconnect();
                    }
                }

                UpdateTimer();
            }
Exemplo n.º 4
0
 public void AddGeofences()
 {
     // Start a request to add geofences
     mRequestType = RequestType.Add;
     // Test for Google Play services after setting the request type
     if (!IsGooglePlayServicesAvailable)
     {
         Log.Error(Constants.TAG, "Unable to add geofences - Google Play services unavailable.");
         return;
     }
     // Create a new location client object. Since this activity implements ConnectionCallbacks and OnConnectionFailedListener,
     // it can be used as the listener for both parameters
     apiClient = new GoogleApiClientBuilder(this, this, this)
                 .AddApi(LocationServices.API)
                 .Build();
     // If a request is not already underway
     if (!mInProgress)
     {
         // Indicate that a request is underway
         mInProgress = true;
         // Request a connection from the client to Location Services
         apiClient.Connect();
     }
     else
     {
         // A request is already underway, so disconnect the client and retry the request
         apiClient.Disconnect();
         apiClient.Connect();
     }
 }
Exemplo n.º 5
0
		protected override void OnStop ()
		{
			base.OnStop ();
			if (mGoogleApiClient.IsConnected) {
				mGoogleApiClient.Disconnect ();
			}
		}
Exemplo n.º 6
0
        public void OnConnected(Bundle p0)
        {
            Log.Debug("ActRecognition", "Connected");
            if (currentRequest == ConnectionUpdateRequest.None)
            {
                return;
            }

            if (callbackIntent == null)
            {
                var intent = new Intent(context, typeof(BikrActivityService));
                callbackIntent = PendingIntent.GetService(context, Resource.Id.bikr_intent_activity, intent, PendingIntentFlags.UpdateCurrent);
            }
            if (currentRequest == ConnectionUpdateRequest.Start)
            {
                api.RequestActivityUpdates(client, (int)desiredDelay, callbackIntent);
                Log.Info("ActRecognition", "Enabling activity updates w/ {0}", desiredDelay.ToString());
            }
            else
            {
                api.RemoveActivityUpdates(client, callbackIntent);
                Log.Info("ActRecognition", "Disabling activity updates");
            }
            currentRequest = ConnectionUpdateRequest.None;
            client.Disconnect();
        }
Exemplo n.º 7
0
        protected override void OnStop()
        {
            logVerbose("Activity onStop, disconnecting GoogleApiClient");

            mGoogleApiClient.Disconnect();
            base.OnStop();
        }
Exemplo n.º 8
0
        /// <summary>
        /// Handles incoming intents
        /// </summary>
        /// <param name="intent">The intent sent by Location Services. This Intent is provided to Location Services (inside a PendingIntent)
        /// when AddGeofences() is called</param>
        protected override void OnHandleIntent(Android.Content.Intent intent)
        {
            // First check for errors
            var geofencingEvent = GeofencingEvent.FromIntent(intent);

            if (geofencingEvent.HasError)
            {
                int errorCode = geofencingEvent.ErrorCode;
                Log.Error(Constants.TAG, "Location Services error: " + errorCode);
            }
            else
            {
                // Get the type of Geofence transition (i.e. enter or exit in this sample).
                int transitionType = geofencingEvent.GeofenceTransition;
                // Create a DataItem when a user enters one of the geofences. The wearable app will receie this and create a
                // notification to prompt him/her to check in
                if (transitionType == Geofence.GeofenceTransitionEnter)
                {
                    // Connect to the Google Api service in preparation for sending a DataItem
                    mGoogleApiClient.BlockingConnect(Constants.CONNECTION_TIME_OUT_MS, TimeUnit.Milliseconds);
                    // Get the geofence ID triggered. Note that only one geofence can be triggered at a time in this example, but in some cases
                    // you might want to consider the full list of geofences triggered
                    string triggeredGeofenceId = geofencingEvent.TriggeringGeofences[0].RequestId;
                    // Create a DataItem with this geofence's id. The wearable can use this to create a notification
                    PutDataMapRequest putDataMapRequest = PutDataMapRequest.Create(Constants.GEOFENCE_DATA_ITEM_PATH);
                    putDataMapRequest.DataMap.PutString(Constants.KEY_GEOFENCE_ID, triggeredGeofenceId);
                    if (mGoogleApiClient.IsConnected)
                    {
                        WearableClass.DataApi.PutDataItem(
                            mGoogleApiClient, putDataMapRequest.AsPutDataRequest()).Await();
                    }
                    else
                    {
                        Log.Error(Constants.TAG, "Failed to send data item: " + putDataMapRequest +
                                  " - disconnected from Google Play Services");
                    }
                    mGoogleApiClient.Disconnect();
                }
                else if (Geofence.GeofenceTransitionExit == transitionType)
                {
                    // Delete the data item when leaving a geofence region
                    mGoogleApiClient.BlockingConnect(Constants.CONNECTION_TIME_OUT_MS, TimeUnit.Milliseconds);
                    WearableClass.DataApi.DeleteDataItems(mGoogleApiClient, Constants.GEOFENCE_DATA_ITEM_URI).Await();
                    mGoogleApiClient.Disconnect();
                }
            }
        }
Exemplo n.º 9
0
 void ILocationListener.OnLocationChanged(Location location)
 {
     Mvx.Resolve <IMvxMessenger>().Publish(new ProgressMessage(ViewModel, true));
     Mvx.Resolve <ICacheService>().CurrentLat = location.Latitude;
     Mvx.Resolve <ICacheService>().CurrentLng = location.Longitude;
     apiClient.Disconnect();
     ViewModel.CheckPlacesCommand.Execute();
 }
Exemplo n.º 10
0
 /**
  * Disconnect from Google Play Services when the activity stops
  */
 protected override void OnStop()
 {
     if (googleApiClient.IsConnected)
     {
         googleApiClient.Disconnect();
     }
     base.OnStop();
 }
Exemplo n.º 11
0
 protected override void OnStop()
 {
     if (client != null)
     {
         client.Disconnect();
     }
     base.OnStop();
 }
Exemplo n.º 12
0
 protected override void OnDestroy()
 {
     if (mGoogleApiClient.IsConnected)
     {
         mGoogleApiClient.Disconnect();
     }
     base.OnDestroy();
 }
Exemplo n.º 13
0
 protected override void OnStop()
 {
     if (mGoogleApiClient.IsConnected)
     {
         WearableClass.NodeApi.RemoveListener(mGoogleApiClient, this);
     }
     mGoogleApiClient.Disconnect();
     base.OnStop();
 }
Exemplo n.º 14
0
        protected override void OnStop()
        {
            base.OnStop();
            Log.Debug(TAG, "onStop");

            if (mGoogleApiClient != null)
            {
                mGoogleApiClient.Disconnect();
            }
        }
Exemplo n.º 15
0
 protected override void OnStop()
 {
     if (!mResolvingError)
     {
         WearableClass.DataApi.RemoveListener(mGoogleApiClient, this);
         WearableClass.MessageApi.RemoveListener(mGoogleApiClient, this);
         WearableClass.NodeApi.RemoveListener(mGoogleApiClient, this);
         mGoogleApiClient.Disconnect();
     }
     base.OnStop();
 }
Exemplo n.º 16
0
        protected override void OnHandleIntent(Intent intent)
        {
            google_api_client.BlockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.Milliseconds);

            if (Log.IsLoggable(TAG, LogPriority.Verbose))
            {
                Log.Verbose(TAG, "FindPhoneService.OnHandleEvent");
            }

            if (google_api_client.IsConnected)
            {
                bool alarmOn = false;
                if (intent.Action == ACTION_TOGGLE_ALARM)
                {
                    var result = WearableClass.DataApi.GetDataItems(google_api_client).Await().JavaCast <DataItemBuffer>();
                    if (result.Status.IsSuccess)
                    {
                        if (result.Count == 1)
                        {
                            alarmOn = DataMap.FromByteArray((result.Get(0).JavaCast <IDataItem>()).GetData()).GetBoolean(FIELD_ALARM_ON, false);
                        }
                        else
                        {
                            Log.Error(TAG, "Unexpected number of DataItems found.\n" +
                                      "\tExpected: 1\n" +
                                      "\tActual: " + result.Count);
                        }
                    }
                    else if (Log.IsLoggable(TAG, LogPriority.Debug))
                    {
                        Log.Debug(TAG, "OnHandleIntent: failed to get current alarm state");
                    }

                    result.Close();
                    alarmOn = !alarmOn;
                    string notificationText = alarmOn ? GetString(Resource.String.turn_alarm_on) : GetString(Resource.String.turn_alarm_off);
                    MainActivity.UpdateNotification(this, notificationText);
                }

                var putDataMapRequest = PutDataMapRequest.Create(PATH_SOUND_ALARM);
                putDataMapRequest.DataMap.PutBoolean(FIELD_ALARM_ON, alarmOn);
                WearableClass.DataApi.PutDataItem(google_api_client, putDataMapRequest.AsPutDataRequest()).Await();
            }
            else
            {
                Log.Error(TAG, "Failed to toggle alarm on phone - Client disconnected from Google Play Services");
            }
            google_api_client.Disconnect();
        }
Exemplo n.º 17
0
 public void disconnectGoogleAPI()
 {
     if (_googleAPI != null && _googleAPI.IsConnected)
     {
         if (_googleAPI.IsConnectionCallbacksRegistered(this))
         {
             _googleAPI.UnregisterConnectionCallbacks(this);
         }
         if (_googleAPI.IsConnectionFailedListenerRegistered(this))
         {
             _googleAPI.UnregisterConnectionFailedListener(this);
         }
         _googleAPI.Disconnect();
     }
 }
Exemplo n.º 18
0
        public void OnResult(Java.Lang.Object result)
        {
            googleApiClient.Disconnect();
            IDataApiDeleteDataItemsResult deleteDataItemsResult;

            try
            {
                deleteDataItemsResult = result.JavaCast <IDataApiDeleteDataItemsResult>();
            }
            catch {
                return;
            }
            if (!deleteDataItemsResult.Status.IsSuccess)
            {
                Log.Error(Tag, "DismissWearableNotification(): Failed to delete IDataItem");
            }
        }
Exemplo n.º 19
0
 public void OnAddGeofencesResult(int statusCode, string[] geofenceRequestIds)
 {
     // Log if adding the geofences was successful
     if (LocationStatusCodes.Success == statusCode)
     {
         if (Log.IsLoggable(Constants.TAG, LogPriority.Debug))
         {
             Log.Debug(Constants.TAG, "Added geofences successfully.");
         }
     }
     else
     {
         Log.Error(Constants.TAG, "Failed to add geofences. Status code: " + statusCode);
     }
     // turn off the in progress flag and disconnect the client
     mInProgress = false;
     apiClient.Disconnect();
 }
Exemplo n.º 20
0
        protected override void OnHandleIntent(Android.Content.Intent intent)
        {
            mGoogleApiClient.BlockingConnect(TIME_OUT, TimeUnit.Milliseconds);
            Android.Net.Uri dataItemUri = intent.Data;
            if (Log.IsLoggable(Constants.TAG, LogPriority.Verbose))
            {
                Log.Verbose(Constants.TAG, "DeleteService.OnHandleIntent = " + dataItemUri);
            }
            if (mGoogleApiClient.IsConnected)
            {
                IDataApiDeleteDataItemsResult result = WearableClass.DataApi
                                                       .DeleteDataItems(mGoogleApiClient, dataItemUri).Await().JavaCast <IDataApiDeleteDataItemsResult>();
                if (result.Status.IsSuccess && !intent.GetBooleanExtra(Constants.EXTRA_SILENT, false))
                {
                    // Show the success animaton on the watch unless Silent extra is true.
                    StartConfirmationActivity(ConfirmationActivity.SuccessAnimation, GetString(Resource.String.delete_successful));
                }
                else
                {
                    if (Log.IsLoggable(Constants.TAG, LogPriority.Verbose))
                    {
                        Log.Verbose(Constants.TAG, "DeleteService.OnHandleIntent: Failed to delete dataITem:"
                                    + dataItemUri);
                    }

                    // Show the failure animation on the watch unless Silent extra is true.
                    if (!intent.GetBooleanExtra(Constants.EXTRA_SILENT, false))
                    {
                        StartConfirmationActivity(ConfirmationActivity.FailureAnimation, GetString(Resource.String.delete_unsuccessful));
                    }
                }
            }
            else
            {
                Log.Error(Constants.TAG, "Failed to delete data item: " + dataItemUri +
                          " - Client disconnected from Google Play Services");
                // Show the failure animation on the watch unless Silent extra is true.
                if (!intent.GetBooleanExtra(Constants.EXTRA_SILENT, false))
                {
                    StartConfirmationActivity(ConfirmationActivity.FailureAnimation, GetString(Resource.String.delete_unsuccessful));
                }
            }
            mGoogleApiClient.Disconnect();
        }
Exemplo n.º 21
0
        void Teardown(bool selectDefaultRoute)
        {
            Console.WriteLine("Teardown");

            if (_apiClient != null)
            {
                if (_applicationStarted)
                {
                    _applicationStarted = false;
                    _hasJoined          = false;
                    if (_apiClient.IsConnected || _apiClient.IsConnecting)
                    {
                        try
                        {
                            CastClass.CastApi.LeaveApplication(_apiClient);
                            if (_channel != null)
                            {
                                CastClass.CastApi.RemoveMessageReceivedCallbacks(
                                    _apiClient,
                                    MyChannel.CastNamespace);
                                _channel = null;
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Exception while removing channel - {0}", e);
                        }
                        _apiClient.Disconnect();
                    }
                }
                _apiClient = null;
            }

            if (selectDefaultRoute)
            {
                _mediaRouter.SelectRoute(_mediaRouter.DefaultRoute);
            }
            _selectedDevice = null;

            _textGuess.Text = string.Empty;
            UpdateEnabledStates();
        }
        protected override void OnHandleIntent(Android.Content.Intent intent)
        {
            if (Constants.ACTION_CHECK_IN.Equals(intent.Action))
            {
                // In a real app, code for checking in would go here. For this sample, we will simply disaply a success animation
                StartConfirmationActivity(ConfirmationActivity.SuccessAnimation, GetString(Resource.String.check_in_success));
                // Dismiss the check-in notification
                GetSystemService(NotificationService).JavaCast <NotificationManager> ().Cancel(Constants.NOTIFICATION_ID);
            }
            else if (!Constants.ACTION_DELETE_DATA_ITEM.Equals(intent.Action))
            {
                // The only possible actions should be checking in or dismissing the notification
                // (which causes an intent with ACTION_DELETE_DATA_ITEM)
                Log.Error(Constants.TAG, "Unrecognized Action: " + intent.Action);
                return;
            }

            // Regardless of the action, delete the DataItem (we are only handling intents if the notification is dismissed or if the user
            // has chosen to check in, either of which would be completed at this point
            mGoogleApiClient.BlockingConnect(Constants.CONNECTION_TIME_OUT_MS, TimeUnit.Milliseconds);
            Android.Net.Uri dataItemUri = intent.Data;
            if (mGoogleApiClient.IsConnected)
            {
                var result = WearableClass.DataApi.DeleteDataItems(mGoogleApiClient, dataItemUri).Await().JavaCast <IDataApiDeleteDataItemsResult> ();
                if (!result.Status.IsSuccess)
                {
                    Log.Error(Constants.TAG, "CheckInAndDeleteDataItemsService.OnHandleIntent: " +
                              "Failed to delete dataItem: " + dataItemUri);
                }
                else if (Log.IsLoggable(Constants.TAG, LogPriority.Debug))
                {
                    Log.Debug(Constants.TAG, "Successfully deleted data item: " + dataItemUri);
                }
            }
            else
            {
                Log.Error(Constants.TAG, "Failed to delete data item: " + dataItemUri
                          + " - Client disconnected from Google Play Services");
            }
            mGoogleApiClient.Disconnect();
        }
Exemplo n.º 23
0
 protected override void OnPause()
 {
     base.OnPause();
     OverridePendingTransition(Resource.Animation.slide_in_left, Resource.Animation.slide_out_right);
     if (apiClient.IsConnected)
     {
         LocationServices.FusedLocationApi.RemoveLocationUpdates(apiClient, this);
         apiClient.Disconnect();
     }
     try
     {
         if (builder != null)
         {
             builder.Cancel();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
 }
        protected override void OnHandleIntent(Intent intent)
        {
            google_api_client.BlockingConnect(Constants.CONNECT_TIMEOUT_MS, TimeUnit.Milliseconds);
            Android.Net.Uri dataItemUri = intent.Data;
            if (!google_api_client.IsConnected)
            {
                Log.Error(TAG, "Failed to update data item " + dataItemUri
                          + " because client is disconnected from Google Play Services");
                return;
            }
            var dataItemResult = WearableClass.DataApi.GetDataItem(
                google_api_client, dataItemUri).Await().JavaCast <IDataApiDataItemResult>();
            var putDataMapRequest = PutDataMapRequest
                                    .CreateFromDataMapItem(DataMapItem.FromDataItem(dataItemResult.DataItem));
            var dataMap = putDataMapRequest.DataMap;

            dataMap.PutBoolean(Constants.QUESTION_WAS_DELETED, true);
            var request = putDataMapRequest.AsPutDataRequest();

            WearableClass.DataApi.PutDataItem(google_api_client, request).Await();
            google_api_client.Disconnect();
        }
Exemplo n.º 25
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            //mGoogleApiClient = new GoogleApiClientBuilder(this).AddApi(Plus.Api).AddScope(new Scope(Scopes.Games)).Build();

            // create an instance of Google API client and specify the Play services
            // and scopes to use. In this example, we specify that the app wants
            // access to the Games, Plus, and Cloud Save services and scopes.
            GoogleApiClientBuilder builder = new GoogleApiClientBuilder(this, this, this);

            builder.AddApi(GamesClass.Api).AddScope(GamesClass.ScopeGames);
            mGoogleApiClient = builder.Build();

            mMatch = new MatchInfo(this);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById <Button>(Resource.Id.myButton);

            button.Click += delegate
            {
                mMatch.IncrementClickCount();
            };

            Button StartMatch = FindViewById <Button>(Resource.Id.StartMatchBtn);

            StartMatch.Click += delegate
            {
                if (!mGoogleApiClient.IsConnected)
                {
                    Toast.MakeText(this, "Sign In First", ToastLength.Long).Show();
                    return;
                }

                Toast.MakeText(this, "StartMatch.Click", ToastLength.Long).Show();

                Intent intent = GamesClass.TurnBasedMultiplayer.GetSelectOpponentsIntent(mGoogleApiClient, 1, 1, true);
                StartActivityForResult(intent, RC_SELECT_PLAYERS);
            };

            Button InboxButton = FindViewById <Button>(Resource.Id.InboxBtn);

            InboxButton.Click += delegate
            {
                if (!mGoogleApiClient.IsConnected)
                {
                    Toast.MakeText(this, "Sign In First", ToastLength.Long).Show();
                    return;
                }

                Toast.MakeText(this, "InboxButton.Click", ToastLength.Long).Show();

                Intent intent = GamesClass.TurnBasedMultiplayer.GetInboxIntent(mGoogleApiClient);
                StartActivityForResult(intent, RC_OPEN_INBOX);
            };

            Button TurnButton = FindViewById <Button>(Resource.Id.TakeTurnBtn);

            TurnButton.Click += delegate
            {
                mMatch.EndTurn();
            };

            Button SingInButton = FindViewById <Button>(Resource.Id.SignInBtn);

            SingInButton.Click += delegate
            {
                if (mGoogleApiClient.IsConnected || mGoogleApiClient.IsConnecting)
                {
                    Toast.MakeText(this, "Already Signed In.", ToastLength.Long).Show();
                    return;
                }

                mGoogleApiClient.Connect();
            };

            Button SingOutButton = FindViewById <Button>(Resource.Id.SignOutBtn);

            SingOutButton.Click += delegate
            {
                if (mGoogleApiClient == null)
                {
                    Toast.MakeText(this, "Google API is Null. Fatal Error.", ToastLength.Long).Show();
                    return;
                }

                if (!mGoogleApiClient.IsConnected && !mGoogleApiClient.IsConnecting)
                {
                    Toast.MakeText(this, "Already Signed Out.", ToastLength.Long).Show();
                    return;
                }

                mGoogleApiClient.Disconnect();
            };
        }
Exemplo n.º 26
0
 protected override void OnStop()
 {
     base.OnStop();
     client.Disconnect();
 }
Exemplo n.º 27
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 GoogleApiClientBuilder (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);
            }
        }
Exemplo n.º 28
0
 protected override void OnPause()
 {
     base.OnPause();
     OverridePendingTransition(Resource.Animation.slide_in_left, Resource.Animation.slide_out_right);
     apiClient.Disconnect();
 }
Exemplo n.º 29
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // If you want to understand the life cycle more, you can use below command to turn on
            // verbose logging for this Activity on your testing device:
            // adb shell setprop log.tag.SignInActivity VERBOSE
            mIsLogVerbose = Android.Util.Log.IsLoggable(TAG, Android.Util.LogPriority.Verbose);

            SetContentView(Resource.Layout.sign_in_activity);

            restoreState(savedInstanceState);

            logVerbose("Activity onCreate, creating new GoogleApiClient");

            mGoogleApiClient = buildGoogleApiClient(false);

            mSignInStatus        = FindViewById <TextView> (Resource.Id.sign_in_status);
            mSignInButton        = FindViewById <SignInButton> (Resource.Id.sign_in_button);
            mSignInButton.Click += (sender, e) => {
                if (!mGoogleApiClient.IsConnecting)
                {
                    int available = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this);
                    if (available != ConnectionResult.Success)
                    {
                        ShowDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES);
                        return;
                    }

                    mSignInClicked     = true;
                    mSignInStatus.Text = GetString(Resource.String.signing_in_status);
                    resolveSignInError();
                }
            };

            mServerAuthCodeDisabledLabel      = FindViewById <TextView> (Resource.Id.server_auth_code_disabled);
            mServerAuthCodeResetButton        = FindViewById <View>(Resource.Id.server_auth_code_reset_button);
            mServerAuthCodeResetButton.Click += (sender, e) => {
                mServerAuthCodeRequired.Set(true);
            };
            if (!isUsingOfflineAccess())
            {
                mServerAuthCodeDisabledLabel.Visibility = ViewStates.Visible;
                mServerAuthCodeResetButton.Visibility   = ViewStates.Gone;
            }
            else
            {
                mServerAuthCodeDisabledLabel.Visibility = ViewStates.Gone;
                mServerAuthCodeResetButton.Visibility   = ViewStates.Visible;
            }

            mSignOutButton        = FindViewById <View> (Resource.Id.sign_out_button);
            mSignOutButton.Click += (sender, e) => {
                if (mGoogleApiClient.IsConnected)
                {
                    mGoogleApiClient.ClearDefaultAccountAndReconnect();
                }
            };
            mRevokeAccessButton        = FindViewById(Resource.Id.revoke_access_button);
            mRevokeAccessButton.Click += (sender, e) => {
                mServerAuthCodeRequired.Set(true);
                if (mGoogleApiClient.IsConnected)
                {
                    PlusClass.AccountApi.RevokeAccessAndDisconnect(mGoogleApiClient).SetResultCallback <Statuses> (result => {
                        if (result.IsSuccess)
                        {
                            mSignInStatus.SetText(Resource.String.revoke_access_status);
                        }
                        else
                        {
                            mSignInStatus.SetText(Resource.String.revoke_access_error_status);
                        }
                        mGoogleApiClient.Reconnect();
                    });

                    updateButtons(false /* isSignedIn */);
                }
            };

            mScopeSelector = FindViewById <ToggleButton> (Resource.Id.scope_selection_toggle);
            mScopeSelector.CheckedChange += (sender, e) => {
                mGoogleApiClient.Disconnect();
                // Since we changed the configuration, the cached connection result is no longer
                // valid.
                mConnectionResult = null;
                mGoogleApiClient  = buildGoogleApiClient(e.IsChecked);
                mGoogleApiClient.Connect();
            };


            if (Build.VERSION.SdkInt >= BuildVersionCodes.Honeycomb)
            {
                ActionBar.SetDisplayHomeAsUpEnabled(true);
            }
        }
Exemplo n.º 30
0
		public void AddGeofences()
		{
			// Start a request to add geofences
			mRequestType = RequestType.Add;
			// Test for Google Play services after setting the request type
			if (!IsGooglePlayServicesAvailable) {
				Log.Error (Constants.TAG, "Unable to add geofences - Google Play services unavailable.");
				return;
			}
			// Create a new location client object. Since this activity implements ConnectionCallbacks and OnConnectionFailedListener,
			// it can be used as the listener for both parameters
			apiClient = new GoogleApiClientBuilder (this, this, this)
				.AddApi (LocationServices.API)
				.Build ();
			// If a request is not already underway
			if (!mInProgress) {
				// Indicate that a request is underway
				mInProgress = true;
				// Request a connection from the client to Location Services
				apiClient.Connect ();
			} else {
				// A request is already underway, so disconnect the client and retry the request
				apiClient.Disconnect ();
				apiClient.Connect ();
			}
		}
Exemplo n.º 31
0
 protected override void OnStop()
 {
     googleApiClient.Disconnect();
     base.OnStop();
 }
Exemplo n.º 32
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 GoogleApiClientBuilder(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);
            }
        }
Exemplo n.º 33
0
        protected override void OnCreate (Bundle savedInstanceState) 
        {
            base.OnCreate (savedInstanceState);
            // If you want to understand the life cycle more, you can use below command to turn on
            // verbose logging for this Activity on your testing device:
            // adb shell setprop log.tag.SignInActivity VERBOSE
            mIsLogVerbose = Android.Util.Log.IsLoggable (TAG, Android.Util.LogPriority.Verbose);

            SetContentView (Resource.Layout.sign_in_activity);

            restoreState (savedInstanceState);

            logVerbose("Activity onCreate, creating new GoogleApiClient");

            mGoogleApiClient = buildGoogleApiClient (false);

            mSignInStatus = FindViewById<TextView> (Resource.Id.sign_in_status);
            mSignInButton = FindViewById<SignInButton> (Resource.Id.sign_in_button);
            mSignInButton.Click += (sender, e) => {
                if (!mGoogleApiClient.IsConnecting) {
                    int available = GooglePlayServicesUtil.IsGooglePlayServicesAvailable (this);
                    if (available != ConnectionResult.Success) {
                        ShowDialog (DIALOG_GET_GOOGLE_PLAY_SERVICES);
                        return;
                    }

                    mSignInClicked = true;
                    mSignInStatus.Text = GetString (Resource.String.signing_in_status);
                    resolveSignInError();
                }
            };

            mServerAuthCodeDisabledLabel = FindViewById<TextView> (Resource.Id.server_auth_code_disabled);
            mServerAuthCodeResetButton = FindViewById<View>(Resource.Id.server_auth_code_reset_button);
            mServerAuthCodeResetButton.Click += (sender, e) => {
                mServerAuthCodeRequired.Set (true);
            };
            if (!isUsingOfflineAccess()) {
                mServerAuthCodeDisabledLabel.Visibility = ViewStates.Visible;
                mServerAuthCodeResetButton.Visibility = ViewStates.Gone;
            } else {
                mServerAuthCodeDisabledLabel.Visibility = ViewStates.Gone;
                mServerAuthCodeResetButton.Visibility = ViewStates.Visible;
            }

            mSignOutButton = FindViewById<View> (Resource.Id.sign_out_button);
            mSignOutButton.Click += (sender, e) => {
                if (mGoogleApiClient.IsConnected)
                    mGoogleApiClient.ClearDefaultAccountAndReconnect ();
            };
            mRevokeAccessButton = FindViewById(Resource.Id.revoke_access_button);
            mRevokeAccessButton.Click += (sender, e) => {
                mServerAuthCodeRequired.Set (true);
                if (mGoogleApiClient.IsConnected) {
                    PlusClass.AccountApi.RevokeAccessAndDisconnect (mGoogleApiClient).SetResultCallback<Statuses> (result => {
                                if (result.IsSuccess) {
                                    mSignInStatus.SetText(Resource.String.revoke_access_status);
                                } else {
                                    mSignInStatus.SetText(Resource.String.revoke_access_error_status);
                                }
                                mGoogleApiClient.Reconnect ();
                    });
                       
                    updateButtons (false /* isSignedIn */);
                }
            };

            mScopeSelector = FindViewById<ToggleButton> (Resource.Id.scope_selection_toggle);
            mScopeSelector.CheckedChange += (sender, e) => {
                mGoogleApiClient.Disconnect ();
                // Since we changed the configuration, the cached connection result is no longer
                // valid.
                mConnectionResult = null;
                mGoogleApiClient = buildGoogleApiClient (e.IsChecked);
                mGoogleApiClient.Connect();
            };


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