@Override
  public void onMessageReceived(MessageEvent messageEvent) {

    if (!messageEvent.getPath().equalsIgnoreCase(AppConstants.PATH_REQUEST_WEATHER)) return;

    if (mGoogleApiClient == null) {
      mGoogleApiClient =
          new GoogleApiClient.Builder(this)
              .addConnectionCallbacks(this)
              .addOnConnectionFailedListener(this)
              .addApi(Wearable.API)
              .build();
    }

    if (!mGoogleApiClient.isConnected()) {
      ConnectionResult connectionResult = mGoogleApiClient.blockingConnect(30, TimeUnit.SECONDS);

      if (!connectionResult.isSuccess()) {
        Log.e(LOG_TAG, "Failed to connect to GoogleApiClient.");
        return;
      }
    }

    Context context = getApplicationContext();
    Cursor weatherData = getWearableWeatherData(context);
    if (weatherData != null && weatherData.moveToFirst()) {
      // Send Data Item with weather data
      sendWeatherData(weatherData, context);
    } else {
      Log.d(LOG_TAG, "No weather data");
    }
  }
Example #2
0
    @Override
    public void run() {
      // check for STORAGE permission
      if (!canWriteToStorage()) return;

      SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(mActivity);
      String driveAccount =
          SP.getString(
              mActivity.getResources().getString(R.string.PROPERTY_googledrive_account),
              "<Not Set>");

      if (driveAccount.equals("<Not Set>")) return;
      GoogleApiClient googleApiClient =
          new GoogleApiClient.Builder(mActivity)
              .addApi(Drive.API)
              .addScope(Drive.SCOPE_FILE)
              .setAccountName(driveAccount)
              .addConnectionCallbacks(m_me)
              .addOnConnectionFailedListener(m_me)
              .build();

      googleApiClient.blockingConnect();
      if (!googleApiClient.isConnected()) return;

      if (mTeamNumber >= 0) {
        syncPhotosForTeam(googleApiClient, mTeamNumber);
      } else {
        mRequester = null;

        // TODO: loop over all folders in the photos dir
      }
    }
Example #3
0
 @Override
 protected void onHandleIntent(Intent intent) {
   GoogleApiClient googleApiClient =
       new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
   ConnectionResult connectionResult = googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
   if (!connectionResult.isSuccess()) {
     Log.e(TAG, "Failed to connect to GoogleApiClient: " + connectionResult.getErrorCode());
     return;
   }
   // Read all DataItems
   DataItemBuffer dataItemBuffer = Wearable.DataApi.getDataItems(googleApiClient).await();
   if (!dataItemBuffer.getStatus().isSuccess()) {
     Log.e(TAG, "Error getting all data items: " + dataItemBuffer.getStatus().getStatusMessage());
   }
   Iterator<DataItem> dataItemIterator = dataItemBuffer.singleRefIterator();
   boolean foundArtwork = false;
   while (dataItemIterator.hasNext()) {
     DataItem dataItem = dataItemIterator.next();
     foundArtwork = foundArtwork || processDataItem(googleApiClient, dataItem);
   }
   dataItemBuffer.release();
   if (!foundArtwork
       && intent != null
       && intent.getBooleanExtra(SHOW_ACTIVATE_NOTIFICATION_EXTRA, false)) {
     ActivateMuzeiIntentService.maybeShowActivateMuzeiNotification(this);
   }
   googleApiClient.disconnect();
 }
  /** @brief This function starts the GPS */
  private void stopLocation() {
    // Check if we need to set up Google API
    if (sGPSIsOn) {
      if (sGoogleApi == null) {
        // Build API
        sGoogleApi =
            new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Thank the 6 God for blockingConnect
        ConnectionResult what = sGoogleApi.blockingConnect();
      }

      if (sLocationIntent == null) {
        Intent intent = new Intent(this, InnerLocationService.class);
        sLocationIntent =
            PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
      }
      if (!sQuickGPSIsOn) {
        InnerLocationService.sPreviousLocation = null;
        InnerLocationService.sCurrentLocation = null;
      }

      LocationServices.FusedLocationApi.removeLocationUpdates(sGoogleApi, sLocationIntent);
      sGPSIsOn = false;
      sQuickGPSIsOn = false;
    }
  }
 @Override
 protected SmartLock doInBackground(SmartLock... smartLocks) {
   Log.v(TAG, "Connecting GoogleApiClient....");
   final SmartLock smartLock = smartLocks[0];
   GoogleApiClient client = smartLock.getCredentialClient();
   ConnectionResult result = client.blockingConnect(5, TimeUnit.SECONDS);
   if (!result.isSuccess()) {
     Log.e(TAG, "Failed to connect with GoogleApiClient with code " + result.getErrorCode());
   }
   return smartLock;
 }
 /**
  * Handles incoming intents.
  *
  * @param intent The Intent sent by Location Services. This Intent is provided to Location
  *     Services (inside a PendingIntent) when addGeofences() is called.
  */
 @Override
 protected void onHandleIntent(Intent intent) {
   GeofencingEvent geoFenceEvent = GeofencingEvent.fromIntent(intent);
   if (geoFenceEvent.hasError()) {
     int errorCode = geoFenceEvent.getErrorCode();
     Log.e("onHandleIntent", "Location Services error: " + errorCode);
     showToast(this, "Click here. Error : " + errorCode);
   } else {
     int transitionType = geoFenceEvent.getGeofenceTransition();
     if (Geofence.GEOFENCE_TRANSITION_ENTER == transitionType) {
       mGoogleApiClient.blockingConnect(Constants.CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
       String triggeredGeoFenceId = geoFenceEvent.getTriggeringGeofences().get(0).getRequestId();
       showToast(
           this,
           "You are here at "
               + GeoFenceCRUD.getGeoFence(
                   geoFenceEvent.getTriggeringGeofences().get(0).getRequestId()));
     } else if (Geofence.GEOFENCE_TRANSITION_EXIT == transitionType) {
       mGoogleApiClient.blockingConnect(Constants.CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
       showToast(this, "Leaving ");
     }
   }
 }
  private Location getLocation() {
    // Check if we need to set up Google API
    if (sGoogleApi == null) {
      // Build API
      sGoogleApi =
          new GoogleApiClient.Builder(this)
              .addConnectionCallbacks(this)
              .addOnConnectionFailedListener(this)
              .addApi(LocationServices.API)
              .build();

      // Thank the 6 God for blockingConnect
      ConnectionResult block = sGoogleApi.blockingConnect();
    }

    Location last = LocationServices.FusedLocationApi.getLastLocation(sGoogleApi);

    return last;
  }
  /** @brief This function starts the GPS */
  private void startLocation(boolean quick) {
    // Check if we need to set up Google API
    if (!sGPSIsOn) {
      Log.e(TAG, "starting location?");
      if (sGoogleApi == null) {
        // Build API
        sGoogleApi =
            new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Thank the 6 God for blockingConnect
        ConnectionResult what = sGoogleApi.blockingConnect();
      }

      if (sLocationIntent == null) {
        Intent intent = new Intent(this, InnerLocationService.class);
        sLocationIntent =
            PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
      }

      if (quick) {
        sQuickGPSIsOn = true;
      }

      long interval = quick ? 0 : 20000;
      LocationRequest locRequest = new LocationRequest();
      if (quick) {
        sQuickGPSIsOn = true;
        locRequest.setNumUpdates(2);
      }

      locRequest.setInterval(interval);
      locRequest.setFastestInterval(interval);
      locRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
      LocationServices.FusedLocationApi.requestLocationUpdates(
          sGoogleApi, locRequest, sLocationIntent);
      sGPSIsOn = true;
    }
  }
  /**
   * Appellé à la réception d'un message envoyé depuis la montre
   *
   * @param messageEvent message reçu
   */
  @Override
  public void onMessageReceived(MessageEvent messageEvent) {
    super.onMessageReceived(messageEvent);

    // Ouvre une connexion vers la montre
    ConnectionResult connectionResult = mApiClient.blockingConnect(30, TimeUnit.SECONDS);

    if (!connectionResult.isSuccess()) {
      Log.e(TAG, "Failed to connect to GoogleApiClient.");
      return;
    }

    // traite le message reçu
    final String path = messageEvent.getPath();

    if (path.equals("bonjour")) {

      // Utilise Retrofit pour réaliser un appel REST
      AndroidService androidService =
          new RestAdapter.Builder()
              .setEndpoint(AndroidService.ENDPOINT)
              .build()
              .create(AndroidService.class);

      // Récupère et deserialise le contenu de mon fichier JSON en objet Element
      androidService.getElements(
          new Callback<List<Element>>() {
            @Override
            public void success(List<Element> elements, Response response) {
              envoyerListElements(elements);
            }

            @Override
            public void failure(RetrofitError error) {}
          });
    }
  }
    @Override
    protected Void doInBackground(Void... params) {
      Dexcom dexcom = new Dexcom();

      try {
        String token =
            dexcom.login(
                PreferenceManager.getDefaultSharedPreferences(context).getString("username", ""),
                PreferenceManager.getDefaultSharedPreferences(context).getString("password", ""));
        if (token != null && token.length() > 0 && token.startsWith("\"")) {
          token = token.substring(1, token.length() - 2); // Strip the "s
          SharedPreferences.Editor editor =
              PreferenceManager.getDefaultSharedPreferences(context).edit();
          editor.putString("token", token);
          editor.apply();
          JSONArray a = dexcom.latestGlucoseValues(token, 1440, 1);
          if (a != null && a.length() > 0) {
            JSONObject o = a.getJSONObject(0);
            final int trend = o.getInt("Trend");
            final int value = o.getInt("Value");
            String WT = o.getString("WT");
            final long time = Long.valueOf(WT.substring(6, WT.length() - 2));
            Log.i("DexcomShareDashclock", "Latest glucose reading: " + value + " mg/dL");

            editor.putInt("Trend", trend);
            editor.putInt("Value", value);
            editor.putLong("Time", time);
            editor.apply();

            final GoogleApiClient googleApiClient =
                new GoogleApiClient.Builder(context).addApi(Wearable.API).build();

            ConnectionResult connectionResult =
                googleApiClient.blockingConnect(30, TimeUnit.SECONDS);

            if (!connectionResult.isSuccess()) {
              Log.e("DexcomShareDashclock", "Failed to connect to GoogleApiClient.");
              return null;
            }

            DataMap map = new DataMap();
            map.putInt("trend", trend);
            map.putInt("value", value);
            map.putLong("time", time);

            NodeApi.GetConnectedNodesResult nodes =
                Wearable.NodeApi.getConnectedNodes(googleApiClient).await();
            for (Node node : nodes.getNodes()) {
              Wearable.MessageApi.sendMessage(
                      googleApiClient, node.getId(), "/latest_glucose", map.toByteArray())
                  .await();
            }

            googleApiClient.disconnect();
          }
        } else {
          Log.e("Dexcom", "Response: " + token);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      return null;
    }
 /**
  * This should be used only in WearService. Connects the client to Google Play services. Blocks
  * the connection for a timeout of {@code waitTime} either until succeeds or fails. This is not
  * allowed on the UI thread.
  *
  * @return the result of the connection
  */
 public boolean waitForConnection(int waitTime) {
   ConnectionResult connectionResult =
       mGoogleApiClient.blockingConnect(waitTime, TimeUnit.SECONDS);
   return connectionResult.isSuccess();
 }