Exemple #1
0
        IGoogleApiClient buildGoogleApiClient(bool useProfileScope)
        {
            var builder = new GoogleApiClientBuilder(this)
                          .AddConnectionCallbacks(this)
                          .AddOnConnectionFailedListener(this);

            var serverClientId = GetString(Resource.String.server_client_id);

            if (!string.IsNullOrEmpty(serverClientId))
            {
                builder.RequestServerAuthCode(serverClientId, this);
            }

            if (useProfileScope)
            {
                builder.AddApi(PlusClass.API)
                .AddScope(PlusClass.ScopePlusProfile);
            }
            else
            {
                builder.AddApi(PlusClass.API, new PlusClass.PlusOptions.Builder()
                               .AddActivityTypes(MomentUtil.ACTIONS).Build())
                .AddScope(PlusClass.ScopePlusLogin);
            }

            return(builder.Build());
        }
        async void HandleMessage(IMessageEvent message)
        {
            try
            {
                Android.Util.Log.Info("WearIntegration", "Received Message");
                var client = new GoogleApiClientBuilder(this)
                             .AddApi(WearableClass.Api)
                             .Build();

                var result = client.BlockingConnect(30, Java.Util.Concurrent.TimeUnit.Seconds);
                if (!result.IsSuccess)
                {
                    return;
                }

                var path = message.Path;

                try
                {
                    if (path.StartsWith(TweetsPath))
                    {
                        var viewModel = new TwitterViewModel();

                        await viewModel.ExecuteLoadTweetsCommand();

                        var request = PutDataMapRequest.Create(TweetsPath + "/Answer");
                        var map     = request.DataMap;

                        var tweetMap = new List <DataMap>();
                        foreach (var tweet in viewModel.Tweets)
                        {
                            var itemMap = new DataMap();

                            itemMap.PutLong("CreatedAt", tweet.CreatedAt.Ticks);
                            itemMap.PutString("ScreenName", tweet.ScreenName);
                            itemMap.PutString("Text", tweet.Text);

                            tweetMap.Add(itemMap);
                        }
                        map.PutDataMapArrayList("Tweets", tweetMap);
                        map.PutLong("UpdatedAt", DateTime.UtcNow.Ticks);

                        WearableClass.DataApi.PutDataItem(client, request.AsPutDataRequest());
                    }
                }
                finally
                {
                    client.Disconnect();
                }
            }
            catch (Exception e)
            {
                Android.Util.Log.Error("WearIntegration", e.ToString());
            }
        }
        async void HandleMessage(IMessageEvent message)
        {
            try
            {
                Android.Util.Log.Info("WearIntegration", "Received Message");
                var client = new GoogleApiClientBuilder(this)
                  .AddApi(WearableClass.API)
                  .Build();

                var result = client.BlockingConnect(30, Java.Util.Concurrent.TimeUnit.Seconds);
                if (!result.IsSuccess)
                    return;

                var path = message.Path;

                try
                {

                    if (path.StartsWith(TweetsPath))
                    {

                        var viewModel = new TwitterViewModel();

                        await viewModel.ExecuteLoadTweetsCommand();

                        var request = PutDataMapRequest.Create(TweetsPath + "/Answer");
                        var map = request.DataMap;

                        var tweetMap = new List<DataMap>();
                        foreach (var tweet in viewModel.Tweets)
                        {
                            var itemMap = new DataMap();

                            itemMap.PutLong("CreatedAt", tweet.CreatedAt.Ticks);
                            itemMap.PutString("ScreenName", tweet.ScreenName);
                            itemMap.PutString("Text", tweet.Text);

                            tweetMap.Add(itemMap);
                        }
                        map.PutDataMapArrayList("Tweets", tweetMap);
                        map.PutLong("UpdatedAt", DateTime.UtcNow.Ticks);

                        await WearableClass.DataApi.PutDataItem(client, request.AsPutDataRequest());
                    }
                }
                finally
                {
                    client.Disconnect();
                }
            }
            catch (Exception e)
            {
                Android.Util.Log.Error("WearIntegration", e.ToString());
            }
        }
Exemple #4
0
        async void HandleMessage(IMessageEvent message)
        {
            try {
                Android.Util.Log.Info("WearIntegration", "Received Message");
                var client = new GoogleApiClientBuilder(this)
                             .AddApi(WearableClass.Api)
                             .AddApi(LocationServices.Api)
                             .Build();

                var result = client.BlockingConnect(30, Java.Util.Concurrent.TimeUnit.Seconds);
                if (!result.IsSuccess)
                {
                    return;
                }

                try {
                    var lastLocation = LocationServices.FusedLocationApi.GetLastLocation(client);
                    if (lastLocation == null)
                    {
                        return;
                    }

                    var stations = Hubway.Instance.LastStations;
                    if (stations == null)
                    {
                        stations = await Hubway.Instance.GetStations();
                    }

                    var currentPoint = new GeoPoint {
                        Lat = lastLocation.Latitude,
                        Lon = lastLocation.Longitude
                    };
                    var nearestStations = Hubway.GetStationsAround(stations, currentPoint);

                    using (var stream = new System.IO.MemoryStream()) {
                        GeoUtils.DumpLocation(currentPoint, stream);
                        StationUtils.DumpStations(nearestStations, stream);
                        var bytes = stream.ToArray();
                        WearableClass.MessageApi.SendMessage(client,
                                                             message.SourceNodeId,
                                                             SearchStationPath + "/Answer",
                                                             bytes).Await();
                    }
                } finally {
                    client.Disconnect();
                }
            } catch (Exception e) {
                Android.Util.Log.Error("WearIntegration", e.ToString());
            }
        }
Exemple #5
0
        public GeolocatorImplementation()
        {
            if (IsGooglePlayServicesInstalled())
            {
                var builder = new GoogleApiClientBuilder(this.Context);
                builder.AddApi(LocationServices.Api);
                builder.AddConnectionCallbacks(this);
                builder.AddOnConnectionFailedListener(this);
                _googleAPI = builder.Build();
                //_googleAPI = new GoogleApiClientBuilder(this.Context).AddApi(LocationServices.Api).AddConnectionCallbacks(this).AddOnConnectionFailedListener(this).Build();

                locRequest = new LocationRequest();
            }
            else
            {
                Toast.MakeText(this.Context, "Google Play Services is not installed", ToastLength.Long).Show();
            }
        }
Exemple #6
0
		async void HandleMessage (IMessageEvent message)
		{
			try {
				Android.Util.Log.Info ("WearIntegration", "Received Message");
				var client = new GoogleApiClientBuilder (this)
					.AddApi (WearableClass.Api)
					.AddApi (LocationServices.Api)
					.Build ();

				var result = client.BlockingConnect (30, Java.Util.Concurrent.TimeUnit.Seconds);
				if (!result.IsSuccess)
					return;

				try {
					var lastLocation = LocationServices.FusedLocationApi.GetLastLocation (client);
					if (lastLocation == null)
						return;

					var stations = Hubway.Instance.LastStations;
					if (stations == null)
						stations = await Hubway.Instance.GetStations ();

					var currentPoint = new GeoPoint {
						Lat = lastLocation.Latitude,
						Lon = lastLocation.Longitude
					};
					var nearestStations = Hubway.GetStationsAround (stations, currentPoint);

					using (var stream = new System.IO.MemoryStream ()) {
						GeoUtils.DumpLocation (currentPoint, stream);
						StationUtils.DumpStations (nearestStations, stream);
						var bytes = stream.ToArray ();
						WearableClass.MessageApi.SendMessage (client,
						                                      message.SourceNodeId,
						                                      SearchStationPath + "/Answer",
						                                      bytes).Await ();
					}
				} finally {
					client.Disconnect ();
				}
			} catch (Exception e) {
				Android.Util.Log.Error ("WearIntegration", e.ToString ());
			}
		}
        void CreateClient()
        {
            string id = GamerPlatformSettings.Instance.PlayerId;

            var builder = new GoogleApiClientBuilder(AppMain.Activity, this, this);

            builder.AddApi(Android.Gms.Games.GamesClass.Api);
            builder.AddScope(Android.Gms.Games.GamesClass.ScopeGames);
            builder.SetGravityForPopups((int)GravityForPopups);

            builder.SetViewForPopups(AppMain.Current.RootView);

            if (!string.IsNullOrEmpty(id))
            {
                builder.SetAccountName(id);
            }

            _client = builder.Build();
        }
        void AppReady()
        {
            _isGooglePlayServicesInstalled = IsGooglePlayServicesInstalled();

            if (_isGooglePlayServicesInstalled)
            {
                locRequest = new LocationRequest();

                var builder = new GoogleApiClientBuilder(this);
                builder.AddApi(LocationServices.Api);
                builder.AddConnectionCallbacks(this);
                builder.AddOnConnectionFailedListener(this);
                locClient = builder.Build();
            }
            else
            {
                Log.Error("OnCreate", "Google Play Services is not installed");
                Toast.MakeText(this, "Google Play Services is not installed", ToastLength.Long).Show();
                Finish();
            }
        }
Exemple #9
0
        private void CreateClient()
        {
            // did we log in with a player id already? If so we don't want to ask which account to use
            var settings = this.activity.GetSharedPreferences("googleplayservicessettings", FileCreationMode.Private);
            var id       = settings.GetString("playerid", String.Empty);

            var builder = new GoogleApiClientBuilder(activity, this, this);

            builder.AddApi(Android.Gms.Games.GamesClass.Api);
            builder.AddScope(Android.Gms.Games.GamesClass.ScopeGames);
            builder.SetGravityForPopups((int)GravityForPopups);
            if (ViewForPopups != null)
            {
                builder.SetViewForPopups(ViewForPopups);
            }
            if (!string.IsNullOrEmpty(id))
            {
                builder.SetAccountName(id);
            }
            client = builder.Build();
        }
		protected override void OnHandleIntent (Intent intent)
		{
			if (intent.Action.Equals (ACTION_RESET_QUIZ)) {
				IGoogleApiClient google_api_client = new GoogleApiClientBuilder (this)
					.AddApi (WearableClass.API)
					.Build ();

				ConnectionResult result = google_api_client.BlockingConnect (Constants.CONNECT_TIMEOUT_MS,
					TimeUnit.Milliseconds);
				if (!result.IsSuccess) {
					Log.Error (TAG, "QuizListenerService failed to connect to GoogleApiClient.");
					return;
				}

				var nodes = WearableClass.NodeApi.GetConnectedNodes (google_api_client).Await ().JavaCast<INodeApiGetConnectedNodesResult>();
				foreach (INode node in nodes.Nodes) {
					WearableClass.MessageApi.SendMessage (google_api_client, node.Id, Constants.RESET_QUIZ_PATH,
						new byte[0]);
				}

			}
		}
Exemple #11
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.Login);
            mGoogleSignIn = FindViewById <SignInButton>(Resource.Id.sign_in_button);


            mGoogleSignIn.Click += mGoogleSignIn_Click;

            GoogleApiClientBuilder builder = new GoogleApiClientBuilder(this);

            builder.AddConnectionCallbacks(this);
            builder.AddOnConnectionFailedListener(this);
            builder.AddApi(PlusClass.Api);
            builder.AddScope(PlusClass.ScopePlusProfile);
            builder.AddScope(PlusClass.ScopePlusLogin);

            //Build our IGoogleApiClient
            mGoogleApiClient = builder.Build();
        }
Exemple #12
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

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

            strCooperativa = Intent.GetStringExtra(clsConstantes.strCooperativas);

            mGoogleSingIn = FindViewById <SignInButton>(Resource.Id.sign_in_button);

            mGoogleSingIn.Click += mGoogleSignIn_Click;

            GoogleApiClientBuilder builder = new GoogleApiClientBuilder(this);

            builder.AddConnectionCallbacks(this);
            builder.AddOnConnectionFailedListener(this);
            builder.AddApi(PlusClass.API);
            builder.AddScope(PlusClass.ScopePlusProfile);
            builder.AddScope(PlusClass.ScopePlusLogin);

            mGoogleApiClient = builder.Build();
        }
Exemple #13
0
        protected override void OnHandleIntent(Intent intent)
        {
            if (intent.Action.Equals(ACTION_RESET_QUIZ))
            {
                IGoogleApiClient google_api_client = new GoogleApiClientBuilder(this)
                                                     .AddApi(WearableClass.Api)
                                                     .Build();

                ConnectionResult result = google_api_client.BlockingConnect(Constants.CONNECT_TIMEOUT_MS,
                                                                            TimeUnit.Milliseconds);
                if (!result.IsSuccess)
                {
                    Log.Error(TAG, "QuizListenerService failed to connect to GoogleApiClient.");
                    return;
                }

                var nodes = WearableClass.NodeApi.GetConnectedNodes(google_api_client).Await().JavaCast <INodeApiGetConnectedNodesResult>();
                foreach (INode node in nodes.Nodes)
                {
                    WearableClass.MessageApi.SendMessage(google_api_client, node.Id, Constants.RESET_QUIZ_PATH,
                                                         new byte[0]);
                }
            }
        }
Exemple #14
0
        async void HandleMessage(IMessageEvent message)
        {
            try
            {
                Android.Util.Log.Info("WearIntegration", "Received Message");

                var client = new GoogleApiClientBuilder(this).AddApi(WearableClass.Api).Build();

                var result = client.BlockingConnect(30, Java.Util.Concurrent.TimeUnit.Seconds);
                if (!result.IsSuccess)
                {
                    return;
                }

                var path = message.Path;

                try
                {
                    if (path == answerYesPath)
                    {
                        _votingService.Vote(true);
                    }
                    else if (path == answerNoPath)
                    {
                        _votingService.Vote(false);
                    }
                }
                finally
                {
                    client.Disconnect();
                }
            } catch (Exception e)
            {
                Android.Util.Log.Error("WearIntegration", e.ToString());
            }
        }
		public override void OnDataChanged (DataEventBuffer eventBuffer)
		{
			var events = FreezableUtils.FreezeIterable (eventBuffer);
			eventBuffer.Close ();

			var google_api_client = new GoogleApiClientBuilder (this)
				.AddApi (WearableClass.API)
				.Build ();

			var connectionResult = google_api_client.BlockingConnect (Constants.CONNECT_TIMEOUT_MS,
				                       TimeUnit.Milliseconds);

			if (!connectionResult.IsSuccess) {
				Log.Error (TAG, "QuizListenerService failed to connect to GoogleApiClient.");
				return;
			}

			foreach (var ev in events) {
				var e = ((Java.Lang.Object)ev).JavaCast<IDataEvent> ();
				if (e.Type == DataEvent.TypeChanged) {
					var dataItem = e.DataItem;
					var dataMap = DataMapItem.FromDataItem (dataItem).DataMap;
					if (dataMap.GetBoolean (Constants.QUESTION_WAS_ANSWERED)
					    || dataMap.GetBoolean (Constants.QUESTION_WAS_DELETED)) {
						continue;
					}

					string question = dataMap.GetString (Constants.QUESTION);
					int questionIndex = dataMap.GetInt (Constants.QUESTION_INDEX);
					int questionNum = questionIndex + 1;
					string[] answers = dataMap.GetStringArray (Constants.ANSWERS);
					int correctAnswerIndex = dataMap.GetInt (Constants.CORRECT_ANSWER_INDEX);
					Intent deleteOperation = new Intent (this, typeof(DeleteQuestionService));
					deleteOperation.SetData (dataItem.Uri);
					PendingIntent deleteIntent = PendingIntent.GetService (this, 0,
						                             deleteOperation, PendingIntentFlags.UpdateCurrent);
					//first page of notification contains question as Big Text.
					var bigTextStyle = new Notification.BigTextStyle ()
						.SetBigContentTitle (GetString (Resource.String.question, questionNum))
						.BigText (question);
					var builder = new Notification.Builder (this)
						.SetStyle (bigTextStyle)
						.SetSmallIcon (Resource.Drawable.ic_launcher)
						.SetLocalOnly (true)
						.SetDeleteIntent (deleteIntent);

					//add answers as actions
					var wearableOptions = new Notification.WearableExtender ();
					for (int i = 0; i < answers.Length; i++) {
						Notification answerPage = new Notification.Builder (this)
							.SetContentTitle (question)
							.SetContentText (answers [i])
							.Extend (new Notification.WearableExtender ()
								.SetContentAction (i))
							.Build ();

						bool correct = (i == correctAnswerIndex);
						var updateOperation = new Intent (this, typeof(UpdateQuestionService));
						//Give each intent a unique action.
						updateOperation.SetAction ("question_" + questionIndex + "_answer_" + i);
						updateOperation.SetData (dataItem.Uri);
						updateOperation.PutExtra (UpdateQuestionService.EXTRA_QUESTION_INDEX, questionIndex);
						updateOperation.PutExtra (UpdateQuestionService.EXTRA_QUESTION_CORRECT, correct);
						var updateIntent = PendingIntent.GetService (this, 0, updateOperation,
							                   PendingIntentFlags.UpdateCurrent);
						Notification.Action action = new Notification.Action.Builder (
							                             (int)question_num_to_drawable_id.Get (i), (string)null, updateIntent)
							.Build ();
						wearableOptions.AddAction (action).AddPage (answerPage);
					}
					builder.Extend (wearableOptions);
					Notification notification = builder.Build ();
					((NotificationManager)GetSystemService (NotificationService))
						.Notify (questionIndex, notification);
				} else if (e.Type == DataEvent.TypeDeleted) {
					Android.Net.Uri uri = e.DataItem.Uri;
					//URIs are in the form of "/question/0", "/question/1" etc.
					//We use the question index as the notification id.
					int notificationId = Java.Lang.Integer.ParseInt (uri.LastPathSegment);
					((NotificationManager)GetSystemService (NotificationService))
						.Cancel (notificationId);
				}

				((NotificationManager)GetSystemService (NotificationService))
					.Cancel (QUIZ_REPORT_NOTIF_ID);
			}
			google_api_client.Disconnect ();
		}
Exemple #16
0
        async void HandleMessage(IMessageEvent message)
        {
            try {
                Android.Util.Log.Info("WearIntegration", "Received Message");
                var client = new GoogleApiClientBuilder(this)
                             .AddApi(LocationServices.API)
                             .AddApi(WearableClass.API)
                             .Build();

                var result = client.BlockingConnect(30, Java.Util.Concurrent.TimeUnit.Seconds);
                if (!result.IsSuccess)
                {
                    return;
                }

                var path = message.Path;

                try {
                    var stations = Hubway.Instance.LastStations;
                    if (stations == null)
                    {
                        stations = await Hubway.Instance.GetStations();
                    }

                    if (path.StartsWith(SearchStationPath))
                    {
                        var lastLocation = LocationServices.FusedLocationApi.GetLastLocation(client);
                        if (lastLocation == null)
                        {
                            return;
                        }

                        var currentPoint = new GeoPoint {
                            Lat = lastLocation.Latitude,
                            Lon = lastLocation.Longitude
                        };
                        var nearestStations = Hubway.GetStationsAround(stations, currentPoint, maxItems: 6, minDistance: double.MaxValue);
                        var favManager      = FavoriteManager.Obtain(this);
                        var favorites       = await favManager.GetFavoriteStationIdsAsync();

                        var request = PutDataMapRequest.Create(SearchStationPath + "/Answer");
                        var map     = request.DataMap;

                        var stationMap = new List <DataMap> ();
                        foreach (var station in nearestStations)
                        {
                            var itemMap = new DataMap();

                            itemMap.PutInt("Id", station.Id);

                            var asset = await CreateWearAssetFrom(station);

                            itemMap.PutAsset("Background", asset);

                            string secondary;
                            string primary = StationUtils.CutStationName(station.Name, out secondary);
                            itemMap.PutString("Primary", primary);
                            itemMap.PutString("Secondary", secondary);

                            var distance = GeoUtils.Distance(currentPoint, station.Location);
                            itemMap.PutDouble("Distance", distance);
                            itemMap.PutDouble("Lat", station.Location.Lat);
                            itemMap.PutDouble("Lon", station.Location.Lon);

                            itemMap.PutInt("Bikes", station.BikeCount);
                            itemMap.PutInt("Racks", station.EmptySlotCount);

                            itemMap.PutBoolean("IsFavorite", favorites.Contains(station.Id));

                            stationMap.Add(itemMap);
                        }
                        map.PutDataMapArrayList("Stations", stationMap);
                        map.PutLong("UpdatedAt", DateTime.UtcNow.Ticks);

                        await WearableClass.DataApi.PutDataItem(client, request.AsPutDataRequest());
                    }
                    else
                    {
                        var uri   = new Uri("wear://watch" + path);
                        var query = uri.GetComponents(UriComponents.Query, UriFormat.Unescaped);
                        var parts = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped).Split('/');

                        var action = parts[parts.Length - 2];
                        var id     = int.Parse(parts.Last());

                        if (action == FavoriteAction)
                        {
                            var favorites = FavoriteManager.Obtain(this);
                            handler.Post(() => {
                                if (query == "add")
                                {
                                    favorites.AddToFavorite(id);
                                }
                                else
                                {
                                    favorites.RemoveFromFavorite(id);
                                }
                            });
                        }
                    }
                } finally {
                    client.Disconnect();
                }
            } catch (Exception e) {
                Android.Util.Log.Error("WearIntegration", e.ToString());
                AnalyticsHelper.LogException("WearIntegration", e);
            }
        }
Exemple #17
0
        public override void OnDataChanged(DataEventBuffer eventBuffer)
        {
            var events = FreezableUtils.FreezeIterable(eventBuffer);

            eventBuffer.Close();

            var google_api_client = new GoogleApiClientBuilder(this)
                                    .AddApi(WearableClass.API)
                                    .Build();

            var connectionResult = google_api_client.BlockingConnect(Constants.CONNECT_TIMEOUT_MS,
                                                                     TimeUnit.Milliseconds);

            if (!connectionResult.IsSuccess)
            {
                Log.Error(TAG, "QuizListenerService failed to connect to GoogleApiClient.");
                return;
            }

            foreach (var ev in events)
            {
                var e = ((Java.Lang.Object)ev).JavaCast <IDataEvent> ();
                if (e.Type == DataEvent.TypeChanged)
                {
                    var dataItem = e.DataItem;
                    var dataMap  = DataMapItem.FromDataItem(dataItem).DataMap;
                    if (dataMap.GetBoolean(Constants.QUESTION_WAS_ANSWERED) ||
                        dataMap.GetBoolean(Constants.QUESTION_WAS_DELETED))
                    {
                        continue;
                    }

                    string   question           = dataMap.GetString(Constants.QUESTION);
                    int      questionIndex      = dataMap.GetInt(Constants.QUESTION_INDEX);
                    int      questionNum        = questionIndex + 1;
                    string[] answers            = dataMap.GetStringArray(Constants.ANSWERS);
                    int      correctAnswerIndex = dataMap.GetInt(Constants.CORRECT_ANSWER_INDEX);
                    Intent   deleteOperation    = new Intent(this, typeof(DeleteQuestionService));
                    deleteOperation.SetData(dataItem.Uri);
                    PendingIntent deleteIntent = PendingIntent.GetService(this, 0,
                                                                          deleteOperation, PendingIntentFlags.UpdateCurrent);
                    //first page of notification contains question as Big Text.
                    var bigTextStyle = new Notification.BigTextStyle()
                                       .SetBigContentTitle(GetString(Resource.String.question, questionNum))
                                       .BigText(question);
                    var builder = new Notification.Builder(this)
                                  .SetStyle(bigTextStyle)
                                  .SetSmallIcon(Resource.Drawable.ic_launcher)
                                  .SetLocalOnly(true)
                                  .SetDeleteIntent(deleteIntent);

                    //add answers as actions
                    var wearableOptions = new Notification.WearableExtender();
                    for (int i = 0; i < answers.Length; i++)
                    {
                        Notification answerPage = new Notification.Builder(this)
                                                  .SetContentTitle(question)
                                                  .SetContentText(answers [i])
                                                  .Extend(new Notification.WearableExtender()
                                                          .SetContentAction(i))
                                                  .Build();

                        bool correct         = (i == correctAnswerIndex);
                        var  updateOperation = new Intent(this, typeof(UpdateQuestionService));
                        //Give each intent a unique action.
                        updateOperation.SetAction("question_" + questionIndex + "_answer_" + i);
                        updateOperation.SetData(dataItem.Uri);
                        updateOperation.PutExtra(UpdateQuestionService.EXTRA_QUESTION_INDEX, questionIndex);
                        updateOperation.PutExtra(UpdateQuestionService.EXTRA_QUESTION_CORRECT, correct);
                        var updateIntent = PendingIntent.GetService(this, 0, updateOperation,
                                                                    PendingIntentFlags.UpdateCurrent);
                        Notification.Action action = new Notification.Action.Builder(
                            (int)question_num_to_drawable_id.Get(i), (string)null, updateIntent)
                                                     .Build();
                        wearableOptions.AddAction(action).AddPage(answerPage);
                    }
                    builder.Extend(wearableOptions);
                    Notification notification = builder.Build();
                    ((NotificationManager)GetSystemService(NotificationService))
                    .Notify(questionIndex, notification);
                }
                else if (e.Type == DataEvent.TypeDeleted)
                {
                    Android.Net.Uri uri = e.DataItem.Uri;
                    //URIs are in the form of "/question/0", "/question/1" etc.
                    //We use the question index as the notification id.
                    int notificationId = Java.Lang.Integer.ParseInt(uri.LastPathSegment);
                    ((NotificationManager)GetSystemService(NotificationService))
                    .Cancel(notificationId);
                }

                ((NotificationManager)GetSystemService(NotificationService))
                .Cancel(QUIZ_REPORT_NOTIF_ID);
            }
            google_api_client.Disconnect();
        }
Exemple #18
0
        private IGoogleApiClient PrepClient()
        {
            if (apiClient == null)
            {
                GoogleApiClientBuilder builder = new GoogleApiClientBuilder(this)
                .AddConnectionCallbacks(this)
                .AddOnConnectionFailedListener(this)
                .AddApi(LocationServices.Api);

                apiClient = builder.Build();
            }

            return apiClient;
        }
        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();
            };
        }
		private void CreateClient() {

			// did we log in with a player id already? If so we don't want to ask which account to use
			var settings = this.activity.GetSharedPreferences ("googleplayservicessettings", FileCreationMode.Private);
			var id = settings.GetString ("playerid", String.Empty);

			var builder = new GoogleApiClientBuilder (activity, this, this);
			builder.AddApi (Android.Gms.Games.GamesClass.Api);
			builder.AddScope (Android.Gms.Games.GamesClass.ScopeGames);
			builder.SetGravityForPopups ((int)GravityForPopups);
			if (ViewForPopups != null)
				builder.SetViewForPopups (ViewForPopups);
			if (!string.IsNullOrEmpty (id)) {
				builder.SetAccountName (id);
			}
			client = builder.Build ();
		}
        IGoogleApiClient buildGoogleApiClient(bool useProfileScope) 
        {
            var builder = new GoogleApiClientBuilder (this)
                .AddConnectionCallbacks (this)
                .AddOnConnectionFailedListener (this);

            var serverClientId = GetString (Resource.String.server_client_id);

            if (!string.IsNullOrEmpty (serverClientId)) 
                builder.RequestServerAuthCode (serverClientId, this);

            if (useProfileScope) {
                builder.AddApi (PlusClass.API)
                    .AddScope (PlusClass.ScopePlusProfile);
            } else {
                builder.AddApi (PlusClass.API, new PlusClass.PlusOptions.Builder()
                    .AddActivityTypes (MomentUtil.ACTIONS).Build ())
                    .AddScope (PlusClass.ScopePlusLogin);
            }

            return builder.Build ();
        }
 public void Setup()
 {
     _googleSearchEngineApiClientBuilder = new GoogleApiClientBuilder();
     _bingSearchEngineApiClientBuilder   = new BingApiClientBuilder();
     _service = new SearchEnginesServices(_googleSearchEngineApiClientBuilder.Build(), _bingSearchEngineApiClientBuilder.Build());
 }
Exemple #23
0
		async void HandleMessage (IMessageEvent message)
		{
			try {
				Android.Util.Log.Info ("WearIntegration", "Received Message");
				var client = new GoogleApiClientBuilder (this)
					.AddApi (LocationServices.API)
					.AddApi (WearableClass.API)
					.Build ();
				
				var result = client.BlockingConnect (30, Java.Util.Concurrent.TimeUnit.Seconds);
				if (!result.IsSuccess)
					return;

				var path = message.Path;

				try {
					var stations = Hubway.Instance.LastStations;
					if (stations == null)
						stations = await Hubway.Instance.GetStations ();

					if (path.StartsWith (SearchStationPath)) {
						var lastLocation = LocationServices.FusedLocationApi.GetLastLocation (client);
						if (lastLocation == null)
							return;

						var currentPoint = new GeoPoint {
							Lat = lastLocation.Latitude,
							Lon = lastLocation.Longitude
						};
						var nearestStations = Hubway.GetStationsAround (stations, currentPoint, maxItems: 6, minDistance: double.MaxValue);
						var favManager = FavoriteManager.Obtain (this);
						var favorites = await favManager.GetFavoriteStationIdsAsync ();

						var request = PutDataMapRequest.Create (SearchStationPath + "/Answer");
						var map = request.DataMap;

						var stationMap = new List<DataMap> ();
						foreach (var station in nearestStations) {
							var itemMap = new DataMap ();

							itemMap.PutInt ("Id", station.Id);

							var asset = await CreateWearAssetFrom (station);
							itemMap.PutAsset ("Background", asset);

							string secondary;
							string primary = StationUtils.CutStationName (station.Name, out secondary);
							itemMap.PutString ("Primary", primary);
							itemMap.PutString ("Secondary", secondary);

							var distance = GeoUtils.Distance (currentPoint, station.Location);
							itemMap.PutDouble ("Distance", distance);
							itemMap.PutDouble ("Lat", station.Location.Lat);
							itemMap.PutDouble ("Lon", station.Location.Lon);

							itemMap.PutInt ("Bikes", station.BikeCount);
							itemMap.PutInt ("Racks", station.EmptySlotCount);

							itemMap.PutBoolean ("IsFavorite", favorites.Contains (station.Id));

							stationMap.Add (itemMap);
						}
						map.PutDataMapArrayList ("Stations", stationMap);
						map.PutLong ("UpdatedAt", DateTime.UtcNow.Ticks);

						await WearableClass.DataApi.PutDataItem (client, request.AsPutDataRequest ());
					} else {
						var uri = new Uri ("wear://watch" + path);
						var query = uri.GetComponents (UriComponents.Query, UriFormat.Unescaped);
						var parts = uri.GetComponents (UriComponents.Path, UriFormat.Unescaped).Split ('/');

						var action = parts[parts.Length - 2];
						var id = int.Parse (parts.Last ());

						if (action == FavoriteAction) {
							var favorites = FavoriteManager.Obtain (this);
							handler.Post (() => {
								if (query == "add")
									favorites.AddToFavorite (id);
								else
									favorites.RemoveFromFavorite (id);
							});
						}
					}
				} finally {
					client.Disconnect ();
				}
			} catch (Exception e) {
				Android.Util.Log.Error ("WearIntegration", e.ToString ());
				AnalyticsHelper.LogException ("WearIntegration", e);
			}
		}