Example #1
0
        public override async void OnDataChanged(DataEventBuffer dataEvents)
        {
            LOGD(Tag, "OnDataChanged: " + dataEvents);
            IList events = FreezableUtils.FreezeIterable(dataEvents);

            dataEvents.Close();
            if (!googleApiClient.IsConnected)
            {
                ConnectionResult connectionResult = googleApiClient.BlockingConnect(30, TimeUnit.Seconds);
                if (!connectionResult.IsSuccess)
                {
                    Log.Error(Tag, "DataLayerListenerService failed to connect to GoogleApiClient");
                    return;
                }
            }

            // Loop through the events and send a message back to the node that created the data item
            foreach (var ev in events)
            {
                var e   = ((Java.Lang.Object)ev).JavaCast <IDataEvent> ();
                var uri = e.DataItem.Uri;
                if (CountPath.Equals(CountPath))
                {
                    // Get the node ID of the node that created the date item from the host portion of the Uri
                    string nodeId = uri.Host;
                    // Set the data of the message to the bytes of the Uri
                    byte[] payload = Encoding.UTF8.GetBytes(uri.ToString());

                    // Send the rpc
                    await WearableClass.MessageApi.SendMessageAsync(googleApiClient, nodeId, DataItemReceivedPath, payload);
                }
            }
        }
Example #2
0
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

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


            _client = new GoogleApiClient.Builder(this)
                      .AddConnectionCallbacks(this)
                      .AddOnConnectionFailedListener(r => WriteLine("Connection failed"))
                      .AddApi(NearbyClass.MessagesApi)

                      .Build();

            await Task.Run(() => _client.BlockingConnect());

            var status = await NearbyClass.Messages.GetPermissionStatusAsync(_client);

            if (status.IsSuccess)
            {
                Subscribe();
            }
            else
            {
                status.StartResolutionForResult(this, ConnectionResult.ResolutionRequired);
            }
        }
        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();
        }
Example #4
0
        public void OnDataChanged(DataEventBuffer dataEvents)
        {
            if (!googleApiClient.IsConnected)
            {
                var connectionResult = googleApiClient.BlockingConnect(30, TimeUnit.Seconds);
                if (!connectionResult.IsSuccess)
                {
                    Log.Error(Tag, "DataLayerListenerService failed to connect to GoogleApiClient");
                    return;
                }
            }

            adapter.Timer.UserLoggedIn = true;
            foreach (var data in dataEvents)
            {
                if (data != null && data.Type == DataEvent.TypeChanged && data.DataItem.Uri.Path == Common.TimeEntryListPath)
                {
                    OnDataChanged(data.DataItem);
                }
            }

            if (CollectionChanged != null)
            {
                CollectionChanged(this, EventArgs.Empty);
            }
        }
        /// <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();
                }
            }
        }
        protected override void Initialize()
        {
            base.Initialize();

            // check for availability of Google Play Services
            int googlePlayServicesAvailability = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(Application.Context);

            if (googlePlayServicesAvailability != ConnectionResult.Success)
            {
                string message = "Google Play Services are not available on this device.";

                if (googlePlayServicesAvailability == ConnectionResult.ServiceVersionUpdateRequired)
                {
                    message += " Please update your phone's Google Play Services app using the App Store. Then restart your study.";
                }

                message += " Email the study organizers and tell them you received the following error code:  " + googlePlayServicesAvailability;

                // the problem we've encountered is potentially fixable, so do not throw a NotSupportedException, as doing this would
                // disable the probe and prevent any future restart attempts from succeeding.
                throw new Exception(message);
            }

            // connect awareness client
            _awarenessApiClient = new GoogleApiClient.Builder(Application.Context).AddApi(Awareness.Api)

                                  .AddConnectionCallbacks(

                bundle =>
            {
                SensusServiceHelper.Get().Logger.Log("Connected to Google Awareness API.", LoggingLevel.Normal, GetType());
            },

                status =>
            {
                SensusServiceHelper.Get().Logger.Log("Connection to Google Awareness API suspended. Status:  " + status, LoggingLevel.Normal, GetType());
            })

                                  .Build();

            _awarenessApiClient.BlockingConnect();

            if (_awarenessApiClient.IsConnected)
            {
                // we need location permission in order to snapshot / fence the user's location.
                if (SensusServiceHelper.Get().ObtainPermission(Permission.Location) != PermissionStatus.Granted)
                {
                    string error = "Geolocation is not permitted on this device. Cannot start location fences.";
                    SensusServiceHelper.Get().FlashNotificationAsync(error);
                }
            }
            else
            {
                throw new Exception("Failed to connect with Google Awareness API.");
            }
        }
Example #7
0
 public override void OnDataChanged(DataEventBuffer dataEvents)
 {
     if (!googleApiClient.IsConnected)
     {
         ConnectionResult connectionResult = googleApiClient.BlockingConnect(30, TimeUnit.Seconds);
         if (!connectionResult.IsSuccess)
         {
             Log.Error(Tag, "DataLayerListenerService failed to connect to GoogleApiClient");
             return;
         }
     }
 }
Example #8
0
        public static void LogOut()
        {
            new Thread(() =>
            {
                ConnectionResult result = mGoogleApiClient?.BlockingConnect((long)1.5, Java.Util.Concurrent.TimeUnit.Seconds);

                if (mGoogleApiClient.IsConnected)
                {
                    Auth.GoogleSignInApi.RevokeAccess(mGoogleApiClient).SetResultCallback(new SignOutResultCallback());
                }
            }).Start();
        }
Example #9
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();
        }
Example #10
0
 public void connectme()
 {
     try
     {
         google_api_client = new GoogleApiClient.Builder(this)
                             .AddApi(WearableClass.API)
                             .AddConnectionCallbacks(this)
                             .AddOnConnectionFailedListener(this)
                             .Build();
         google_api_client.Connect();
         google_api_client.BlockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.Milliseconds);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
Example #11
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();
        }
Example #12
0
        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();
        }
Example #13
0
        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();
        }
Example #14
0
        private async void LoadIssues()
        {
            var sharedPreferences = GetSharedPreferences("IssueApp", FileCreationMode.Private);
            var key = sharedPreferences.GetString("Key", null);

            if (key == null)
            {
                var editText    = new EditText(this);
                var alertDialog = new AlertDialog.Builder(this);
                alertDialog.SetIcon(Android.Resource.Drawable.IcDialogInfo);
                alertDialog.SetTitle("Redmine認証キー").SetView(editText).SetPositiveButton("OK", async(sender, args) =>
                {
                    var service = new RedmineService(editText.Text);
                    var check   = await service.CheckAsync();
                    if (check)
                    {
                        var preferencesEditor = sharedPreferences.Edit();
                        preferencesEditor.PutString("Key", editText.Text);
                        preferencesEditor.Apply();
                        LoadIssues();
                    }
                    else
                    {
                        LoadIssues();
                    }
                }).SetNegativeButton(Properties.Resources.Host + "を開く", (sender, args) =>
                {
                    var uri    = Uri.Parse(Properties.Resources.Url);
                    var intent = new Intent(Intent.ActionView, uri);
                    StartActivity(intent);
                    LoadIssues();
                }).Show();
                return;
            }

            var progressDialog = new ProgressDialog(this);

            progressDialog.SetMessage("Redmineから読み込み中");
            progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner);
            progressDialog.SetButton("この表示を消す", (sender, args) => progressDialog.Hide());
            progressDialog.Show();

            var redmineService = new RedmineService(key);
            var response       = await redmineService.GetIssues();

            _issues = response.issues;

            foreach (var issue in _issues)
            {
                if (double.IsNaN(issue.lat))
                {
                    continue;
                }

                var markerOptions = new MarkerOptions();
                markerOptions.SetPosition(new LatLng(issue.lat, issue.lng));
                markerOptions.SetTitle(issue.subject);
                _googleMap.AddMarker(markerOptions);
            }

            UpdateList();

            progressDialog.Hide();

            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == Permission.Granted)
            {
                _googleMap.MyLocationEnabled = true;
            }
            else
            {
                RequestPermissions(new[] { Manifest.Permission.AccessFineLocation, Manifest.Permission.AccessCoarseLocation }, 0x01);
            }

            _googleApiClient = new GoogleApiClient.Builder(this)
                               .AddApi(LocationServices.API)
                               .AddConnectionCallbacks(this)
                               .Build();
            await Task.Run(() =>
            {
                _googleApiClient.BlockingConnect();
            });
        }