Java Code Examples for com.google.android.gms.wearable.PutDataMapRequest#create()

The following examples show how to use com.google.android.gms.wearable.PutDataMapRequest#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DigitalWatchFaceUtil.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Overwrites the current config {@link DataItem}'s {@link DataMap} with {@code newConfig}.
 * If the config DataItem doesn't exist, it's created.
 */
public static void putConfigDataItem(GoogleApiClient googleApiClient, DataMap newConfig, final Callable<Void> callable) {
    PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(PATH_WITH_FEATURE);
    putDataMapRequest.setUrgent();
    DataMap configToPut = putDataMapRequest.getDataMap();
    configToPut.putAll(newConfig);
    Wearable.DataApi.putDataItem(googleApiClient, putDataMapRequest.asPutDataRequest())
            .setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
                @Override
                public void onResult(DataApi.DataItemResult dataItemResult) {
                    try{
                        if (callable != null) {
                            callable.call();
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "Finish callback failed.", e);
                    }
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG, "putDataItem result status: " + dataItemResult.getStatus());
                    }
                }
            });
}
 
Example 2
Source File: WearService.java    From TutosAndroidFrance with MIT License 6 votes vote down vote up
/**
 * Permet d'envoyer une image à la montre
 */
protected void sendImage(String url, int position) {
    //télécharge l'image
    Bitmap bitmap = getBitmapFromURL(url);
    if (bitmap != null) {
        Asset asset = createAssetFromBitmap(bitmap);

        //créé un emplacement mémoire "image/[url_image]"
        final PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/image/" + position);

        //ajoute la date de mise à jour, important pour que les données soient mises à jour
        putDataMapRequest.getDataMap().putString("timestamp", new Date().toString());

        //ajoute l'image à la requête
        putDataMapRequest.getDataMap().putAsset("image", asset);

        //envoie la donnée à la montre
        if (mApiClient.isConnected())
            Wearable.DataApi.putDataItem(mApiClient, putDataMapRequest.asPutDataRequest());
    }
}
 
Example 3
Source File: RemoteSensorManager.java    From SensorDashboard with Apache License 2.0 6 votes vote down vote up
private void filterBySensorIdInBackground(final int sensorId) {
    Log.d(TAG, "filterBySensorId(" + sensorId + ")");

    if (validateConnection()) {
        PutDataMapRequest dataMap = PutDataMapRequest.create("/filter");

        dataMap.getDataMap().putInt(DataMapKeys.FILTER, sensorId);
        dataMap.getDataMap().putLong(DataMapKeys.TIMESTAMP, System.currentTimeMillis());

        PutDataRequest putDataRequest = dataMap.asPutDataRequest();
        Wearable.DataApi.putDataItem(googleApiClient, putDataRequest).setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
            @Override
            public void onResult(DataApi.DataItemResult dataItemResult) {
                Log.d(TAG, "Filter by sensor " + sensorId + ": " + dataItemResult.getStatus().isSuccess());
            }
        });
    }
}
 
Example 4
Source File: WatchUpdaterService.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
private void sendCancelNotificationRequest(String actionstring) {
    if (googleApiClient.isConnected()) {
        PutDataMapRequest dataMapRequest = PutDataMapRequest.create(ACTION_CANCELNOTIFICATION_REQUEST_PATH);
        //unique content
        dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
        dataMapRequest.getDataMap().putString("cancelNotificationRequest", "cancelNotificationRequest");
        dataMapRequest.getDataMap().putString("actionstring", actionstring);

        log.debug("Canceling notification on wear: " + actionstring);

        PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
        debugData("sendCancelNotificationRequest", putDataRequest);
        Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
    } else {
        Log.e("cancelNotificationReq", "No connection to wearable available!");
    }
}
 
Example 5
Source File: WatchServices.java    From WearPay with GNU General Public License v2.0 6 votes vote down vote up
@DebugLog
private void sendToWatch(String code) {
    Bitmap bitmapQR = EncodingHandlerUtils.createQRCode(code, 600);
    Bitmap bitmapBar = EncodingHandlerUtils.createBarcode(code, 600, 200);
    PutDataMapRequest dataMap = PutDataMapRequest.create(Common.PATH_QR_CODE);
    dataMap.getDataMap().putAsset(Common.KEY_QR_CODE, toAsset(bitmapQR));
    dataMap.getDataMap().putAsset(Common.KEY_BAR_CODE, toAsset(bitmapBar));
    PutDataRequest request = dataMap.asPutDataRequest();
    Wearable.DataApi.putDataItem(mGoogleApiClient, request)
            .setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
                @Override
                @DebugLog
                public void onResult(DataApi.DataItemResult dataItemResult) {
                    if (dataItemResult.getStatus().isSuccess()) {
                        System.out.println("发送成功");
                    } else {
                        System.out.println("发送失败");
                    }
                }
            });

    //sendMessageToAllNodes(Common.PATH_CODE, code.getBytes());
}
 
Example 6
Source File: WatchUpdaterService.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
private void sendNotification() {
    if (googleApiClient.isConnected()) {
        PutDataMapRequest dataMapRequest = PutDataMapRequest.create(OPEN_SETTINGS_PATH);
        //unique content
        dataMapRequest.getDataMap().putDouble("timestamp", System.currentTimeMillis());
        dataMapRequest.getDataMap().putString("openSettings", "openSettings");
        PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
        Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
    } else {
        Log.e("OpenSettings", "No connection to wearable available!");
    }
}
 
Example 7
Source File: RetrieveService.java    From wear-notify-for-reddit with Apache License 2.0 5 votes vote down vote up
private void sendPostsToWearable(@NonNull List<Post> posts, @NonNull final String msg,
                                 @Nullable SimpleArrayMap<String, Asset> assets) {
    if (mGoogleApiClient.isConnected()) {
        // convert to json for sending to watch and to save to shared prefs
        // don't need to preserve the order like having separate String lists, can more easily add/remove fields
        PutDataMapRequest mapRequest = PutDataMapRequest.create(Constants.PATH_REDDIT_POSTS);
        DataMap dataMap = mapRequest.getDataMap();

        if (assets != null && !assets.isEmpty()) {
            for (int i = 0; i < assets.size(); i++) {
                dataMap.putAsset(assets.keyAt(i), assets.valueAt(i));
            }
        }

        dataMap.putLong("timestamp", System.currentTimeMillis());
        dataMap.putString(Constants.KEY_REDDIT_POSTS, mGson.toJson(posts));
        dataMap.putBoolean(Constants.KEY_DISMISS_AFTER_ACTION,
                mUserStorage.openOnPhoneDismissesAfterAction());
        dataMap.putIntegerArrayList(Constants.KEY_ACTION_ORDER,
                mWearableActionStorage.getSelectedActionIds());

        PutDataRequest request = mapRequest.asPutDataRequest();
        Wearable.DataApi.putDataItem(mGoogleApiClient, request)
                .setResultCallback(dataItemResult -> {
                    Timber.d(msg + ", final timestamp: " + mUserStorage.getTimestamp() + " result: " + dataItemResult
                            .getStatus());

                    if (dataItemResult.getStatus().isSuccess()) {
                        if (mGoogleApiClient.isConnected()) {
                            mGoogleApiClient.disconnect();
                        }
                    } else {
                        Timber.d("Failed to send posts to wearable " + dataItemResult.getStatus()
                                .getStatusMessage());
                    }
                });
    }
}
 
Example 8
Source File: WatchUpdaterService.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
private void sendBolusProgress(int progresspercent, String status) {
    if (googleApiClient.isConnected()) {
        PutDataMapRequest dataMapRequest = PutDataMapRequest.create(BOLUS_PROGRESS_PATH);
        //unique content
        dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
        dataMapRequest.getDataMap().putString("bolusProgress", "bolusProgress");
        dataMapRequest.getDataMap().putString("progressstatus", status);
        dataMapRequest.getDataMap().putInt("progresspercent", progresspercent);
        PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
        debugData("sendBolusProgress", putDataRequest);
        Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
    } else {
        Log.e("BolusProgress", "No connection to wearable available!");
    }
}
 
Example 9
Source File: Message.java    From DronesWear with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static PendingResult<DataApi.DataItemResult> sendInteractionTypeMessage(int interactionBitfield, GoogleApiClient googleApiClient) {
    PutDataMapRequest dataMapRequest = PutDataMapRequest.create(INTERACTION_TYPE_PATH);
    DataMap dataMap = dataMapRequest.getDataMap();
    //Data set
    dataMap.putInt(VALUE_STR, interactionBitfield);

    // Data Push
    PutDataRequest request = dataMapRequest.asPutDataRequest();
    PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(googleApiClient, request);

    return pendingResult;
}
 
Example 10
Source File: SunsetsWatchFaceUtil.java    From american-sunsets-watch-face with Apache License 2.0 5 votes vote down vote up
/**
 * Overwrites the current config {@link DataItem}'s {@link DataMap} with {@code newConfig}.
 * If the config DataItem doesn't exist, it's created.
 */
public static void putConfigDataItem(GoogleApiClient googleApiClient, DataMap newConfig) {
    PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(PATH_WITH_FEATURE);
    DataMap configToPut = putDataMapRequest.getDataMap();
    configToPut.putAll(newConfig);
    Wearable.DataApi.putDataItem(googleApiClient, putDataMapRequest.asPutDataRequest())
            .setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
                @Override
                public void onResult(DataApi.DataItemResult dataItemResult) {
                    if (Log.isLoggable(TAG, Log.DEBUG)) {
                        Log.d(TAG, "putDataItem result status: " + dataItemResult.getStatus());
                    }
                }
            });
}
 
Example 11
Source File: WatchUpdaterService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private void sendBlob(String path, final byte[] blob) {
    forceGoogleApiConnect();
    if (googleApiClient.isConnected()) {
        final Asset asset = Asset.createFromBytes(blob);
        Log.d(TAG, "sendBlob asset size: " + asset.getData().length);
        final PutDataMapRequest request = PutDataMapRequest.create(path);
        request.getDataMap().putLong("time", new Date().getTime());
        request.getDataMap().putByteArray("asset", blob);
        request.setUrgent();

        final PendingResult result = Wearable.DataApi.putDataItem(googleApiClient, request.asPutDataRequest());

        result.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
            @Override
            public void onResult(DataApi.DataItemResult sendMessageResult) {
                if (!sendMessageResult.getStatus().isSuccess()) {
                    UserError.Log.e(TAG, "ERROR: failed to sendblob Status=" + sendMessageResult.getStatus().getStatusMessage());
                } else {
                    UserError.Log.i(TAG, "Sendblob  Status=: " + sendMessageResult.getStatus().getStatusMessage());
                }
            }
        });

        Log.d(TAG, "sendBlob: Sending asset of size " + blob.length);

    } else {
        Log.e(TAG, "sendBlob: No connection to wearable available!");
    }
}
 
Example 12
Source File: WearService.java    From DaVinci with Apache License 2.0 5 votes vote down vote up
protected void sendElements(final List<Element> elements) {
    final PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/elements/");

    ArrayList<DataMap> elementsDataMap = new ArrayList<>();

    for (int position = 0; position < elements.size(); ++position) {

        DataMap elementDataMap = new DataMap();
        Element element = elements.get(position);
        elementDataMap.putString("timestamp", new Date().toString());

        elementDataMap.putString("titre", element.getTitre());
        elementDataMap.putString("description", element.getDescription());
        elementDataMap.putString("url", element.getUrl());

        elementsDataMap.add(elementDataMap);

    }
    putDataMapRequest.getDataMap().putDataMapArrayList("/list/",elementsDataMap);

    if (mApiClient.isConnected())
        Wearable.DataApi.putDataItem(mApiClient, putDataMapRequest.asPutDataRequest());

    for(int position = 0; position < elements.size(); ++position){
        DaVinciDaemon.with(getApplicationContext()).load(elements.get(position).getUrl()).send();
    }
}
 
Example 13
Source File: WatchUpdaterService.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
private void sendNotification() {
    if (googleApiClient.isConnected()) {
        PutDataMapRequest dataMapRequest = PutDataMapRequest.create(OPEN_SETTINGS_PATH);
        //unique content
        dataMapRequest.getDataMap().putDouble("timestamp", System.currentTimeMillis());
        dataMapRequest.getDataMap().putString("openSettings", "openSettings");
        PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
        Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
    } else {
        Log.e("OpenSettings", "No connection to wearable available!");
    }
}
 
Example 14
Source File: Message.java    From DronesWear with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static PendingResult<DataApi.DataItemResult> sendActionMessage(GoogleApiClient googleApiClient) {
    PutDataMapRequest dataMapRequest = PutDataMapRequest.create(ACTION_PATH);
    actionMessageUri = dataMapRequest.getUri();

    // Data Push
    PutDataRequest request = dataMapRequest.asPutDataRequest();
    PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(googleApiClient, request);

    return pendingResult;
}
 
Example 15
Source File: RequestListenerService.java    From arcgis-runtime-demos-android with Apache License 2.0 4 votes vote down vote up
/**
 * Handles issuing a response to a FeatureType response. A FeatureType response
 * indicates that the Wear devices wants a feature of the specified FeatureType
 * to be collected at the current device location.
 *
 * @param event the MessageEvent from the Wear device
 * @param client the Google API client used to communicate
 */
private void handleFeatureTypeResponse(final MessageEvent event, final GoogleApiClient client) {
  // Create a PutDataMapRequest with the status response path
  final PutDataMapRequest req = PutDataMapRequest.create(STATUS_RESPONSE);
  final DataMap dm = req.getDataMap();
  // Put the current time into the data map, which forces an onDataChanged event (this event
  // only occurs when data actually changes, so putting the time ensures something always changes)
  dm.putLong("Time", System.currentTimeMillis());
  try {
    // Request a single high precision location update
    LocationRequest request = LocationRequest.create()
            .setNumUpdates(1)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationServices.FusedLocationApi.requestLocationUpdates(client, request, new LocationListener() {
      @Override
      public void onLocationChanged(Location location) {
        // When we've got a location, get the FeatureType that matches the specified name
        Log.i("Test", "Received location");
        String featureTypeName = new String(event.getData());
        FeatureType type = null;
        for (FeatureType ft : sArcGISFeatureLayer.getTypes()) {
          if (ft.getName().equals(featureTypeName)) {
            type = ft;
            break;
          }
        }
        // Only proceed if we found a matching type (which we always should)
        if (type != null) {
          // Create a new feature of the specified type at the current location
          Graphic g = sArcGISFeatureLayer.createFeatureWithType(type, new Point(location.getLongitude(), location.getLatitude()));
          // Apply the edit to the service
          sArcGISFeatureLayer.applyEdits(new Graphic[]{g}, null, null, new CallbackListener<FeatureEditResult[][]>() {
            @Override
            public void onCallback(FeatureEditResult[][] featureEditResults) {
              // Check that we have a success and report success
              if (featureEditResults[0].length > 0) {
                FeatureEditResult fer = featureEditResults[0][0];
                if (fer.isSuccess()) {
                  Log.i("Test", "Successfully added feature");
                  // Put a boolean indicating success into the data map
                  dm.putBoolean("success", true);
                } else {
                  Log.e("Test", "Failed to add feature: " + fer.getError().getDescription());
                  // Put a boolean indicating failure into the data map
                  dm.putBoolean("success", false);
                  // Put a string with the reason for failure into the data map
                  dm.putString("reason", "Error code: " + fer.getError().getCode());
                }
              }
              // Put the DataItem into the Data API stream
              Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
            }

            @Override
            public void onError(Throwable throwable) {
              Log.d("Test", "Failed to add new graphic");
              // Put a boolean indicating failure into the data map
              dm.putBoolean("success", false);
              // Put a string with the reason for failure into the data map
              dm.putString("reason", throwable.getLocalizedMessage());
              // Put the DataItem into the Data API stream
              Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
            }
          });
        } else {
          // If we don't have a matching feature type (which should never happen), log an error
          Log.e("Test", "Could not determine type");
          // Put a boolean indicating failure into the data map
          dm.putBoolean("success", false);
          // Put a string with the reason for failure into the data map
          dm.putString("reason", "Specified type not found");
          // Put the DataItem into the Data API stream
          Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
        }
      }
    });
  } catch (SecurityException se) {
    // If we caught an exception trying to get the location, likelihood is that the location
    // permission has not been granted by the user
    Log.e("Test", "Could not access location");
    // Put a boolean indicating failure into the data map
    dm.putBoolean("success", false);
    // Put a string with the reason for failure into the data map
    dm.putString("reason", "Could not access location. Check permissions.");
    // Put the DataItem into the Data API stream
    Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
  }
}
 
Example 16
Source File: WatchUpdaterService.java    From AndroidAPS with GNU Affero General Public License v3.0 4 votes vote down vote up
private void sendStatus() {

        if (googleApiClient.isConnected()) {
            Profile profile = ProfileFunctions.getInstance().getProfile();
            String status = MainApp.gs(R.string.noprofile);
            String iobSum, iobDetail, cobString, currentBasal, bgiString;
            iobSum = iobDetail = cobString = currentBasal = bgiString = "";
            if (profile != null) {
                TreatmentsInterface treatmentsInterface = TreatmentsPlugin.getPlugin();
                treatmentsInterface.updateTotalIOBTreatments();
                IobTotal bolusIob = treatmentsInterface.getLastCalculationTreatments().round();
                treatmentsInterface.updateTotalIOBTempBasals();
                IobTotal basalIob = treatmentsInterface.getLastCalculationTempBasals().round();

                iobSum = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob);
                iobDetail = "(" + DecimalFormatter.to2Decimal(bolusIob.iob) + "|" + DecimalFormatter.to2Decimal(basalIob.basaliob) + ")";
                cobString = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "WatcherUpdaterService").generateCOBString();
                currentBasal = generateBasalString(treatmentsInterface);

                //bgi


                double bgi = -(bolusIob.activity + basalIob.activity) * 5 * Profile.fromMgdlToUnits(profile.getIsfMgdl(), ProfileFunctions.getSystemUnits());
                bgiString = "" + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to1Decimal(bgi);

                status = generateStatusString(profile, currentBasal, iobSum, iobDetail, bgiString);
            }


            //batteries
            int phoneBattery = getBatteryLevel(getApplicationContext());
            String rigBattery = NSDeviceStatus.getInstance().getUploaderStatus().trim();


            long openApsStatus = -1;
            //OpenAPS status
            if (Config.APS) {
                //we are AndroidAPS
                openApsStatus = LoopPlugin.lastRun != null && LoopPlugin.lastRun.lastTBREnact != 0 ? LoopPlugin.lastRun.lastTBREnact : -1;
            } else {
                //NSClient or remote
                openApsStatus = NSDeviceStatus.getOpenApsTimestamp();
            }

            PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NEW_STATUS_PATH);
            //unique content
            dataMapRequest.getDataMap().putString("externalStatusString", status);
            dataMapRequest.getDataMap().putString("iobSum", iobSum);
            dataMapRequest.getDataMap().putString("iobDetail", iobDetail);
            dataMapRequest.getDataMap().putBoolean("detailedIob", SP.getBoolean(R.string.key_wear_detailediob, false));
            dataMapRequest.getDataMap().putString("cob", cobString);
            dataMapRequest.getDataMap().putString("currentBasal", currentBasal);
            dataMapRequest.getDataMap().putString("battery", "" + phoneBattery);
            dataMapRequest.getDataMap().putString("rigBattery", rigBattery);
            dataMapRequest.getDataMap().putLong("openApsStatus", openApsStatus);
            dataMapRequest.getDataMap().putString("bgi", bgiString);
            dataMapRequest.getDataMap().putBoolean("showBgi", SP.getBoolean(R.string.key_wear_showbgi, false));
            dataMapRequest.getDataMap().putInt("batteryLevel", (phoneBattery >= 30) ? 1 : 0);
            PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
            debugData("sendStatus", putDataRequest);
            Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
        } else {
            Log.e("SendStatus", "No connection to wearable available!");
        }
    }
 
Example 17
Source File: FindPhoneService.java    From android-FindMyPhone with Apache License 2.0 4 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "FindPhoneService.onHandleIntent");
    }
    if (mGoogleApiClient.isConnected()) {
        // Set the alarm off by default.
        boolean alarmOn = false;
        if (intent.getAction().equals(ACTION_TOGGLE_ALARM)) {
            // Get current state of the alarm.
            DataItemBuffer result = Wearable.DataApi.getDataItems(mGoogleApiClient).await();
            try {
                if (result.getStatus().isSuccess()) {
                    if (result.getCount() == 1) {
                        alarmOn = DataMap.fromByteArray(result.get(0).getData())
                                .getBoolean(FIELD_ALARM_ON, false);
                    } else {
                        Log.e(TAG, "Unexpected number of DataItems found.\n"
                                + "\tExpected: 1\n"
                                + "\tActual: " + result.getCount());
                    }
                } else if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "onHandleIntent: failed to get current alarm state");
                }
            } finally {
                result.release();
            }
            // Toggle alarm.
            alarmOn = !alarmOn;
            // Change notification text based on new value of alarmOn.
            String notificationText = alarmOn ? getString(R.string.turn_alarm_off)
                    : getString(R.string.turn_alarm_on);
            FindPhoneActivity.updateNotification(this, notificationText);
        }
        // Use alarmOn boolean to update the DataItem - phone will respond accordingly
        // when it receives the change.
        PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(PATH_SOUND_ALARM);
        putDataMapRequest.getDataMap().putBoolean(FIELD_ALARM_ON, alarmOn);
        putDataMapRequest.setUrgent();
        Wearable.DataApi.putDataItem(mGoogleApiClient, putDataMapRequest.asPutDataRequest())
                .await();
    } else {
        Log.e(TAG, "Failed to toggle alarm on phone - Client disconnected from Google Play "
                + "Services");
    }
    mGoogleApiClient.disconnect();
}
 
Example 18
Source File: DataManager.java    From ibm-wearables-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * @return new Data Map Request
 */
private PutDataMapRequest getNewSensorsDataMapRequest(){
    return PutDataMapRequest.create("/sensors");
}
 
Example 19
Source File: GeofenceTransitionsIntentService.java    From AndroidWearable-Samples with Apache License 2.0 4 votes vote down vote up
/**
 * 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) {
    // First check for errors.
    if (LocationClient.hasError(intent)) {
        int errorCode = LocationClient.getErrorCode(intent);
        Log.e(TAG, "Location Services error: " + errorCode);
    } else {
        // Get the type of geofence transition (i.e. enter or exit in this sample).
        int transitionType = LocationClient.getGeofenceTransition(intent);
        // Create a DataItem when a user enters one of the geofences. The wearable app will
        // receive this and create a notification to prompt him/her to check in.
        if (Geofence.GEOFENCE_TRANSITION_ENTER == transitionType) {
            // Connect to the Google Api service in preparation for sending a DataItem.
            mGoogleApiClient.blockingConnect(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 = LocationClient.getTriggeringGeofences(intent).get(0)
                    .getRequestId();
            // Create a DataItem with this geofence's id. The wearable can use this to create
            // a notification.
            final PutDataMapRequest putDataMapRequest =
                    PutDataMapRequest.create(GEOFENCE_DATA_ITEM_PATH);
            putDataMapRequest.getDataMap().putString(KEY_GEOFENCE_ID, triggeredGeofenceId);
            if (mGoogleApiClient.isConnected()) {
                Wearable.DataApi.putDataItem(
                    mGoogleApiClient, putDataMapRequest.asPutDataRequest()).await();
            } else {
                Log.e(TAG, "Failed to send data item: " + putDataMapRequest
                         + " - Client disconnected from Google Play Services");
            }
            mGoogleApiClient.disconnect();
        } else if (Geofence.GEOFENCE_TRANSITION_EXIT == transitionType) {
            // Delete the data item when leaving a geofence region.
            mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
            Wearable.DataApi.deleteDataItems(mGoogleApiClient, GEOFENCE_DATA_ITEM_URI).await();
            mGoogleApiClient.disconnect();
        }
    }
}
 
Example 20
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 4 votes vote down vote up
/**
 * Transfer the required data over to the wearable
 * @param attractions list of attraction data to transfer over
 */
private void sendDataToWearable(List<Attraction> attractions) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();

    // It's OK to use blockingConnect() here as we are running in an
    // IntentService that executes work on a separate (background) thread.
    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    // Limit attractions to send
    int count = attractions.size() > Constants.MAX_ATTRACTIONS ?
            Constants.MAX_ATTRACTIONS : attractions.size();

    ArrayList<DataMap> attractionsData = new ArrayList<>(count);

    for (int i = 0; i < count; i++) {
        Attraction attraction = attractions.get(i);

        Bitmap image = null;
        Bitmap secondaryImage = null;

        try {
            // Fetch and resize attraction image bitmap
            image = Glide.with(this)
                    .load(attraction.imageUrl)
                    .asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(Constants.WEAR_IMAGE_SIZE_PARALLAX_WIDTH, Constants.WEAR_IMAGE_SIZE)
                    .get();

            secondaryImage = Glide.with(this)
                    .load(attraction.secondaryImageUrl)
                    .asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(Constants.WEAR_IMAGE_SIZE_PARALLAX_WIDTH, Constants.WEAR_IMAGE_SIZE)
                    .get();
        } catch (InterruptedException | ExecutionException e) {
            Log.e(TAG, "Exception loading bitmap from network");
        }

        if (image != null && secondaryImage != null) {

            DataMap attractionData = new DataMap();

            String distance = Utils.formatDistanceBetween(
                    Utils.getLocation(this), attraction.location);

            attractionData.putString(Constants.EXTRA_TITLE, attraction.name);
            attractionData.putString(Constants.EXTRA_DESCRIPTION, attraction.description);
            attractionData.putDouble(
                    Constants.EXTRA_LOCATION_LAT, attraction.location.latitude);
            attractionData.putDouble(
                    Constants.EXTRA_LOCATION_LNG, attraction.location.longitude);
            attractionData.putString(Constants.EXTRA_DISTANCE, distance);
            attractionData.putString(Constants.EXTRA_CITY, attraction.city);
            attractionData.putAsset(Constants.EXTRA_IMAGE,
                    Utils.createAssetFromBitmap(image));
            attractionData.putAsset(Constants.EXTRA_IMAGE_SECONDARY,
                    Utils.createAssetFromBitmap(secondaryImage));

            attractionsData.add(attractionData);
        }
    }

    if (connectionResult.isSuccess() && googleApiClient.isConnected()
            && attractionsData.size() > 0) {

        PutDataMapRequest dataMap = PutDataMapRequest.create(Constants.ATTRACTION_PATH);
        dataMap.getDataMap().putDataMapArrayList(Constants.EXTRA_ATTRACTIONS, attractionsData);
        dataMap.getDataMap().putLong(Constants.EXTRA_TIMESTAMP, new Date().getTime());
        PutDataRequest request = dataMap.asPutDataRequest();

        // Send the data over
        DataApi.DataItemResult result =
                Wearable.DataApi.putDataItem(googleApiClient, request).await();

        if (!result.getStatus().isSuccess()) {
            Log.e(TAG, String.format("Error sending data using DataApi (error code = %d)",
                    result.getStatus().getStatusCode()));
        }

    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
    }
    googleApiClient.disconnect();
}