com.google.android.gms.wearable.DataItem Java Examples

The following examples show how to use com.google.android.gms.wearable.DataItem. 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: WatchFaceCompanionConfigActivity.java    From american-sunsets-watch-face with Apache License 2.0 6 votes vote down vote up
@Override // DataApi.DataListener
public void onDataChanged(DataEventBuffer dataEvents) {
    for (DataEvent dataEvent : dataEvents) {
        if (dataEvent.getType() != DataEvent.TYPE_CHANGED) {
            continue;
        }

        DataItem dataItem = dataEvent.getDataItem();
        if (!dataItem.getUri().getPath().equals(SunsetsWatchFaceUtil.PATH_WITH_FEATURE)) {
            continue;
        }

        DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItem);
        DataMap config = dataMapItem.getDataMap();
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Config DataItem updated:" + config);
        }
        updateUiForConfigDataMap(config);
    }
}
 
Example #2
Source File: WearableUtil.java    From APDE with GNU General Public License v2.0 6 votes vote down vote up
public static void sendApkToWatch(Context context, File apkFile, final ResultCallback callback) {
	Uri apkUri = FileProvider.getUriForFile(context, "com.calsignlabs.apde.fileprovider", apkFile);
	Asset asset = Asset.createFromUri(apkUri);
	PutDataMapRequest dataMap = PutDataMapRequest.create("/apk");
	dataMap.getDataMap().putAsset("apk", asset);
	dataMap.getDataMap().putLong("timestamp", System.currentTimeMillis());
	PutDataRequest request = dataMap.asPutDataRequest();
	request.setUrgent();
	
	Task<DataItem> putTask = Wearable.getDataClient(context).putDataItem(request);
	putTask.addOnCompleteListener(new OnCompleteListener<DataItem>() {
		@Override
		public void onComplete(@NonNull Task<DataItem> task) {
			if (task.isSuccessful()) {
				callback.success();
			} else {
				callback.failure();
			}
		}
	});
}
 
Example #3
Source File: MainActivity.java    From wearable with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the data.  Since it specify a client, everyone who is listening to the path, will
 * get the data.
 */
private void sendData(String message) {
    PutDataMapRequest dataMap = PutDataMapRequest.create(datapath);
    dataMap.getDataMap().putString("message", message);
    PutDataRequest request = dataMap.asPutDataRequest();
    request.setUrgent();

    Task<DataItem> dataItemTask = Wearable.getDataClient(this).putDataItem(request);
    dataItemTask
        .addOnSuccessListener(new OnSuccessListener<DataItem>() {
            @Override
            public void onSuccess(DataItem dataItem) {
                Log.d(TAG, "Sending message was successful: " + dataItem);
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "Sending message failed: " + e);
            }
        })
    ;
}
 
Example #4
Source File: MainActivity.java    From wearable with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the data, note this is a broadcast, so we will get the message as well.
 */
private void sendData(String message) {
    PutDataMapRequest dataMap = PutDataMapRequest.create(datapath);
    dataMap.getDataMap().putString("message", message);
    PutDataRequest request = dataMap.asPutDataRequest();
    request.setUrgent();

    Task<DataItem> dataItemTask = Wearable.getDataClient(this).putDataItem(request);
    dataItemTask
        .addOnSuccessListener(new OnSuccessListener<DataItem>() {
            @Override
            public void onSuccess(DataItem dataItem) {
                Log.d(TAG, "Sending message was successful: " + dataItem);
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "Sending message failed: " + e);
            }
        })
    ;
}
 
Example #5
Source File: DataListenerTest.java    From wear with MIT License 6 votes vote down vote up
public void testDataChanged() {
    DataItem item = Mockito.mock(DataItem.class);
    Mockito.when(item.getUri()).thenReturn(Uri.parse(DATA_PATH));

    DataEvent event = Mockito.mock(DataEvent.class);
    Mockito.when(event.getType()).thenReturn(DataEvent.TYPE_CHANGED);
    Mockito.when(event.getDataItem()).thenReturn(item);

    DataListener listener = new DataListener();
    DataListener.Callback callback = Mockito.mock(DataListener.Callback.class);
    listener.addCallback(DATA_PATH, callback);

    // TODO

    Mockito.verify(callback).onDataChanged(event);
    Mockito.verifyNoMoreInteractions(callback);
}
 
Example #6
Source File: WatchFace.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {

    for( DataEvent event : dataEvents ) {
        if( event.getType() == DataEvent.TYPE_CHANGED ) {
            DataItem item = event.getDataItem();
            if( item.getUri().getPath().compareTo( DATA_LAYER_PATH ) == 0 ) {
                DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
                int selectedBackgroundPosition = dataMap.getInt(KEY_BACKGROUND_POSITION);
                TypedArray typedArray = getResources().obtainTypedArray( R.array.background_resource_ids );
                initBackground( typedArray.getResourceId( selectedBackgroundPosition, 0 ) );
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                preferences.edit().putInt( SHARED_PREFERENCE_POSITION, selectedBackgroundPosition ).commit();
                typedArray.recycle();
                invalidate();
            }
        }
    }
}
 
Example #7
Source File: CollectionActivity.java    From arcgis-runtime-demos-android with Apache License 2.0 6 votes vote down vote up
/**
 * Handles a status response. The status response indicates whether the
 * feature was successfully collected or not, and if not, a reason why.
 *
 * @param item the DataItem received from the mobile device
 */
private void handleStatusResponse(DataItem item) {
  // Gets the TextView that will be used to display the status
  TextView text = (TextView) findViewById(R.id.text);
  DataMap dm = DataMapItem.fromDataItem(item).getDataMap();
  boolean success = dm.getBoolean("success");
  // If the event was successfully, show a success message in green
  if (success) {
    text.setText(R.string.collect_success);
    text.setTextColor(Color.GREEN);
  } else {
    // If it failed, show the failure reason in red
    String reason = dm.getString("reason");
    text.setText(String.format("%s\n%s", getString(R.string.collect_failure), reason));
    text.setTextColor(Color.RED);
  }
  // After 2 seconds, finish the activity
  new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
      CollectionActivity.this.finish();
    }
  }, 2000);
}
 
Example #8
Source File: CollectionActivity.java    From arcgis-runtime-demos-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
  Log.i("Test", "Data changed event received");
  // Get the data changed event and handle it appropriately
  for(DataEvent event : dataEventBuffer) {
    if (event.getType() == DataEvent.TYPE_CHANGED) {
      DataItem item = event.getDataItem();
      String path = item.getUri().getPath();
      switch (path) {
        case LAYER_RESPONSE:
          handleLayerResponse(item);
          break;
        case FEATURE_TYPE_RESPONSE:
          handleFeatureTypeResponse(item);
          break;
        case STATUS_RESPONSE:
          handleStatusResponse(item);
          break;
      }
    }
  }
}
 
Example #9
Source File: SensorReceiverService.java    From SensorDashboard with Apache License 2.0 6 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    Log.d(TAG, "onDataChanged()");

    for (DataEvent dataEvent : dataEvents) {
        if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
            DataItem dataItem = dataEvent.getDataItem();
            Uri uri = dataItem.getUri();
            String path = uri.getPath();

            if (path.startsWith("/sensors/")) {
                unpackSensorData(
                    Integer.parseInt(uri.getLastPathSegment()),
                    DataMapItem.fromDataItem(dataItem).getDataMap()
                );
            }
        }
    }
}
 
Example #10
Source File: MessageReceiverService.java    From SensorDashboard with Apache License 2.0 6 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    super.onDataChanged(dataEvents);

    for (DataEvent dataEvent : dataEvents) {
        if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
            DataItem dataItem = dataEvent.getDataItem();
            Uri uri = dataItem.getUri();
            String path = uri.getPath();

            if (path.startsWith("/filter")) {
                DataMap dataMap = DataMapItem.fromDataItem(dataItem).getDataMap();
                int filterById = dataMap.getInt(DataMapKeys.FILTER);
                deviceClient.setSensorFilter(filterById);
            }
        }
    }
}
 
Example #11
Source File: UARTConfigurationsActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * This method read the UART configurations from the DataApi and populates the adapter with them.
 */
private void populateConfigurations() {
	if (googleApiClient.isConnected()) {
		final PendingResult<DataItemBuffer> results = Wearable.DataApi.getDataItems(googleApiClient, Uri.parse("wear:" + Constants.UART.CONFIGURATIONS), DataApi.FILTER_PREFIX);
		results.setResultCallback(dataItems -> {
			final List<UartConfiguration> configurations = new ArrayList<>(dataItems.getCount());
			for (int i = 0; i < dataItems.getCount(); ++i) {
				final DataItem item = dataItems.get(i);
				final long id = ContentUris.parseId(item.getUri());
				final DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
				final UartConfiguration configuration = new UartConfiguration(dataMap, id);
				configurations.add(configuration);
			}
			adapter.setConfigurations(configurations);
			dataItems.release();
		});
	}
}
 
Example #12
Source File: UARTCommandsActivity.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onDataChanged(final DataEventBuffer dataEventBuffer) {
	for (final DataEvent event : dataEventBuffer) {
		final DataItem item = event.getDataItem();
		final long id = ContentUris.parseId(item.getUri());

		// Update the configuration only if ID matches
		if (id != configurationId)
			continue;

		// Configuration added or edited
		if (event.getType() == DataEvent.TYPE_CHANGED) {
			final DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
			final UartConfiguration configuration = new UartConfiguration(dataMap, id);

			// Update UI on UI thread
			runOnUiThread(() -> adapter.setConfiguration(configuration));
		} else if (event.getType() == DataEvent.TYPE_DELETED) {
			// Configuration removed

			// Update UI on UI thread
			runOnUiThread(() -> adapter.setConfiguration(null));
		}
	}
}
 
Example #13
Source File: DigitalWatchFaceService.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
@Override // DataApi.DataListener
public void onDataChanged(DataEventBuffer dataEvents) {
    for (DataEvent dataEvent : dataEvents) {
        if (dataEvent.getType() != DataEvent.TYPE_CHANGED) {
            continue;
        }

        DataItem dataItem = dataEvent.getDataItem();
        if (!dataItem.getUri().getPath().equals(
                DigitalWatchFaceUtil.PATH_WITH_FEATURE)) {
            continue;
        }

        DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItem);
        DataMap config = dataMapItem.getDataMap();
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Config DataItem updated:" + config);
        }
        updateUiForConfigDataMap(config);
    }
}
 
Example #14
Source File: SunsetsWatchFace.java    From american-sunsets-watch-face with Apache License 2.0 6 votes vote down vote up
@Override // DataApi.DataListener
public void onDataChanged(DataEventBuffer dataEvents) {
    for (DataEvent dataEvent : dataEvents) {
        if (dataEvent.getType() != DataEvent.TYPE_CHANGED) {
            continue;
        }

        DataItem dataItem = dataEvent.getDataItem();
        if (!dataItem.getUri().getPath().equals(
                SunsetsWatchFaceUtil.PATH_WITH_FEATURE)) {
            continue;
        }

        DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItem);
        DataMap config = dataMapItem.getDataMap();
        Log.d(TAG, "Config DataItem updated:" + config);

        updateUiForConfigDataMap(config);
    }
}
 
Example #15
Source File: DataApiHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Retrieve wear settings from Wear cloud storage
 */
public void updateSettings(Context context) {
    if (!googleApiClient.isConnected()) {
        if (!blockingConnect()) {
            return;
        }
    }

    ArrayList<DataMap> data;
    DataItemBuffer dataItemBuffer = Wearable.DataApi.getDataItems(googleApiClient).await();

    if (dataItemBuffer.getStatus().isSuccess()) {
        for (DataItem dataItem : dataItemBuffer) {
            DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItem);
            data = dataMapItem.getDataMap().getDataMapArrayList(WearableConstants.EXTRA_SETTINGS);
            if (data != null) {
                ListenerService.extractSettings(data);
                break;
            }
        }
    }
    dataItemBuffer.release();
}
 
Example #16
Source File: SensorReceiverService.java    From wearabird with MIT License 6 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
	for (DataEvent dataEvent : dataEvents) {
		if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
			DataItem dataItem = dataEvent.getDataItem();
			Uri uri = dataItem.getUri();
			String path = uri.getPath();

			if (path.startsWith("/sensors/")) {
				unpackSensorData(
						Integer.parseInt(uri.getLastPathSegment()),
						DataMapItem.fromDataItem(dataItem).getDataMap()
				);
			}
		}
	}
}
 
Example #17
Source File: WearableMainActivity.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
private void addLocationEntry(double latitude, double longitude) {
    if (!mGpsPermissionApproved) {
        return;
    }
    mCalendar.setTimeInMillis(System.currentTimeMillis());
    LocationEntry entry = new LocationEntry(mCalendar, latitude, longitude);
    String path = Constants.PATH + "/" + mCalendar.getTimeInMillis();
    PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(path);
    putDataMapRequest.getDataMap().putDouble(Constants.KEY_LATITUDE, entry.latitude);
    putDataMapRequest.getDataMap().putDouble(Constants.KEY_LONGITUDE, entry.longitude);
    putDataMapRequest.getDataMap()
            .putLong(Constants.KEY_TIME, entry.calendar.getTimeInMillis());
    PutDataRequest request = putDataMapRequest.asPutDataRequest();
    request.setUrgent();

    Task<DataItem> dataItemTask =
            Wearable.getDataClient(getApplicationContext()).putDataItem(request);

    dataItemTask.addOnSuccessListener(dataItem -> {
        Log.d(TAG, "Data successfully sent: " + dataItem.toString());
    });
    dataItemTask.addOnFailureListener(exception -> {
        Log.e(TAG, "AddPoint:onClick(): Failed to set the data, "
                + "exception: " + exception);
    });
}
 
Example #18
Source File: MainActivity.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the asset that was created from the photo we took by adding it to the Data Item store.
 */
private void sendPhoto(Asset asset) {
    PutDataMapRequest dataMap = PutDataMapRequest.create(IMAGE_PATH);
    dataMap.getDataMap().putAsset(IMAGE_KEY, asset);
    dataMap.getDataMap().putLong("time", new Date().getTime());
    PutDataRequest request = dataMap.asPutDataRequest();
    request.setUrgent();

    Task<DataItem> dataItemTask = Wearable.getDataClient(this).putDataItem(request);

    dataItemTask.addOnSuccessListener(
            new OnSuccessListener<DataItem>() {
                @Override
                public void onSuccess(DataItem dataItem) {
                    LOGD(TAG, "Sending image was successful: " + dataItem);
                }
            });
}
 
Example #19
Source File: MainActivity.java    From DronesWear with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    for (DataEvent event : dataEvents) {
        if (event.getType() == DataEvent.TYPE_CHANGED) {
            DataItem dataItem = event.getDataItem();
            switch (Message.getMessageType(dataItem)) {
                case ACTION_TYPE:
                    int productAction = Message.decodeActionTypeMessage(dataItem);
                    onActionTypeChanged(productAction);
                    break;
                case INTERACTION_TYPE:
                    int interactionType = Message.decodeInteractionTypeMessage(dataItem);
                    onInteractionTypeChanged(interactionType);
                    break;
            }

        }
    }
}
 
Example #20
Source File: MainActivity.java    From DronesWear with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onConnected(Bundle bundle) {
    Wearable.DataApi.addListener(mGoogleApiClient, this);

    // get existing data
    PendingResult<DataItemBuffer> results = Wearable.DataApi.getDataItems(mGoogleApiClient);
    results.setResultCallback(new ResultCallback<DataItemBuffer>() {
        @Override
        public void onResult(@NonNull DataItemBuffer dataItems) {
            for (DataItem dataItem : dataItems) {
                switch (Message.getMessageType(dataItem)) {
                    case ACTION_TYPE:
                        int productAction = Message.decodeActionTypeMessage(dataItem);
                        onActionTypeChanged(productAction);
                        break;
                    case INTERACTION_TYPE:
                        int interactionType = Message.decodeInteractionTypeMessage(dataItem);
                        onInteractionTypeChanged(interactionType);
                        break;
                }
            }
            dataItems.release();
        }
    });
}
 
Example #21
Source File: Message.java    From DronesWear with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static MESSAGE_TYPE getMessageType(DataItem dataItem){
    MESSAGE_TYPE messageType = MESSAGE_TYPE.UNKNOWN;
    if (dataItem != null)
    {
        String path = dataItem.getUri().getPath();
        if (ACC_PATH.equalsIgnoreCase(path)) {
            messageType = MESSAGE_TYPE.ACC;
        }
        else if (JOYSTICK_PATH.equalsIgnoreCase(path)) {
            messageType = MESSAGE_TYPE.JOYSTICK;
        }
        else if (INTERACTION_TYPE_PATH.equalsIgnoreCase(path)) {
            messageType = MESSAGE_TYPE.INTERACTION_TYPE;
        }
        else if (ACTION_TYPE_PATH.equalsIgnoreCase(path)) {
            messageType = MESSAGE_TYPE.ACTION_TYPE;
        }
        else if (ACTION_PATH.equalsIgnoreCase(path)) {
            messageType = MESSAGE_TYPE.ACTION;
        }

    }
    return messageType;
}
 
Example #22
Source File: HomeListenerService.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the calendar card associated with the data item.
 */
private void deleteDataItem(DataItem dataItem) {
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "onDataItemDeleted:DataItem=" + dataItem.getUri());
    }
    Integer notificationId = sNotificationIdByDataItemUri.remove(dataItem.getUri());
    if (notificationId != null) {
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(notificationId);
    }
}
 
Example #23
Source File: MainActivity.java    From android-Quiz with Apache License 2.0 5 votes vote down vote up
private void resetDataItems(DataItemBuffer dataItemList) {
    if (mGoogleApiClient.isConnected()) {
        for (final DataItem dataItem : dataItemList) {
            final Uri dataItemUri = dataItem.getUri();
            Wearable.DataApi.getDataItem(mGoogleApiClient, dataItemUri)
                    .setResultCallback(new ResetDataItemCallback());
        }
    } else {
        Log.e(TAG, "Failed to reset data items because client is disconnected from "
                + "Google Play Services");
    }
}
 
Example #24
Source File: MainActivity.java    From android-Quiz with Apache License 2.0 5 votes vote down vote up
/**
 * Clears the current quiz when user clicks on "New Quiz."
 * On this end, this involves clearing the quiz status layout and deleting all DataItems. The
 * wearable will then remove any outstanding question notifications upon receiving this change.
 */
public void newQuiz(View view) {
    clearQuizStatus();
    if (mGoogleApiClient.isConnected()) {
        Wearable.DataApi.getDataItems(mGoogleApiClient)
                .setResultCallback(new ResultCallback<DataItemBuffer>() {
                    @Override
                    public void onResult(DataItemBuffer result) {
                        try {
                            if (result.getStatus().isSuccess()) {
                                List<Uri> dataItemUriList = new ArrayList<Uri>();
                                for (final DataItem dataItem : result) {
                                    dataItemUriList.add(dataItem.getUri());
                                }
                                deleteDataItems(dataItemUriList);
                            } else {
                                if (Log.isLoggable(TAG, Log.DEBUG)) {
                                    Log.d(TAG, "Clear quiz: failed to get Data Items for "
                                            + "deletion");

                                }
                            }
                        } finally {
                            result.release();
                        }
                    }
                });
    } else {
        Log.e(TAG, "Failed to delete data items because client is disconnected from "
                + "Google Play Services");
    }
}
 
Example #25
Source File: MainActivity.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
/**
 * Resets the current quiz when Reset Quiz is pressed.
 */
public void resetQuiz(View view) {
    // Reset quiz status in phone layout.
    for(int i = 0; i < questionsContainer.getChildCount(); i++) {
        LinearLayout questionStatusElement = (LinearLayout) questionsContainer.getChildAt(i);
        TextView questionText = (TextView) questionStatusElement.findViewById(R.id.question);
        TextView questionStatus = (TextView) questionStatusElement.findViewById(R.id.status);
        questionText.setTextColor(Color.WHITE);
        questionStatus.setText(R.string.question_unanswered);
    }
    // Reset data items and notifications on wearable.
    if (mGoogleApiClient.isConnected()) {
        Wearable.DataApi.getDataItems(mGoogleApiClient)
                .setResultCallback(new ResultCallback<DataItemBuffer>() {
                    @Override
                    public void onResult(DataItemBuffer result) {
                        if (result.getStatus().isSuccess()) {
                            List<DataItem> dataItemList = FreezableUtils.freezeIterable(result);
                            result.close();
                            resetDataItems(dataItemList);
                        } else {
                            if (Log.isLoggable(TAG, Log.DEBUG)) {
                                Log.d(TAG, "Reset quiz: failed to get Data Items to reset");
                            }
                        }
                        result.close();
                    }
                });
    } else {
        Log.e(TAG, "Failed to reset data items because client is disconnected from "
                + "Google Play Services");
    }
    setHasQuestionBeenAsked(false);
    mNumCorrect = 0;
    mNumIncorrect = 0;
    mNumSkipped = 0;
}
 
Example #26
Source File: MainActivity.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
private void resetDataItems(List<DataItem> dataItemList) {
    if (mGoogleApiClient.isConnected()) {
        for (final DataItem dataItem : dataItemList) {
            final Uri dataItemUri = dataItem.getUri();
            Wearable.DataApi.getDataItem(mGoogleApiClient, dataItemUri)
                    .setResultCallback(new ResetDataItemCallback());
        }
    } else {
        Log.e(TAG, "Failed to reset data items because client is disconnected from "
                + "Google Play Services");
    }
}
 
Example #27
Source File: MainActivity.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
/**
 * Clears the current quiz when user clicks on "New Quiz."
 * On this end, this involves clearing the quiz status layout and deleting all DataItems. The
 * wearable will then remove any outstanding question notifications upon receiving this change.
 */
public void newQuiz(View view) {
    clearQuizStatus();
    if (mGoogleApiClient.isConnected()) {
        Wearable.DataApi.getDataItems(mGoogleApiClient)
                .setResultCallback(new ResultCallback<DataItemBuffer>() {
                    @Override
                    public void onResult(DataItemBuffer result) {
                        if (result.getStatus().isSuccess()) {
                            List<Uri> dataItemUriList = new ArrayList<Uri>();
                            for (final DataItem dataItem : result) {
                                dataItemUriList.add(dataItem.getUri());
                            }
                            result.close();
                            deleteDataItems(dataItemUriList);
                        } else {
                            if (Log.isLoggable(TAG, Log.DEBUG)) {
                                Log.d(TAG, "Clear quiz: failed to get Data Items for deletion");
                            }
                        }
                        result.close();
                    }
                });
    } else {
        Log.e(TAG, "Failed to delete data items because client is disconnected from "
                + "Google Play Services");
    }
}
 
Example #28
Source File: HomeListenerService.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the check-in notification when the DataItem is deleted.
 * @param dataItem Used only for logging in this sample, but could be used to identify which
 *                 notification to cancel (in this case, there is at most 1 notification).
 */
private void cancelNotificationForDataItem(DataItem dataItem) {
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "onDataItemDeleted:DataItem=" + dataItem.getUri());
    }
    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(NOTIFICATION_ID);
}
 
Example #29
Source File: Message.java    From DronesWear with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int decodeActionTypeMessage(DataItem dataItem) {
    int actionType = -1;
    if (MESSAGE_TYPE.ACTION_TYPE.equals(getMessageType(dataItem))) {
        DataMap dataMap = DataMap.fromByteArray(dataItem.getData());
        actionType =  dataMap.getInt(VALUE_STR);
    }

    return actionType;
}
 
Example #30
Source File: MainActivity.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
private void deleteDataItems(DataItemBuffer dataItems) {
    if (mGoogleApiClient.isConnected()) {
        // Store the DataItem URIs in a List and close the buffer. Then use these URIs
        // to delete the DataItems.
        final List<DataItem> dataItemList = FreezableUtils.freezeIterable(dataItems);
        dataItems.close();
        for (final DataItem dataItem : dataItemList) {
            final Uri dataItemUri = dataItem.getUri();
            // In a real calendar application, this might delete the corresponding calendar
            // event from the calendar data provider. In this sample, we simply delete the
            // DataItem, but leave the phone's calendar data intact.
            Wearable.DataApi.deleteDataItems(mGoogleApiClient, dataItemUri)
                    .setResultCallback(new ResultCallback<DataApi.DeleteDataItemsResult>() {
                        @Override
                        public void onResult(DataApi.DeleteDataItemsResult deleteResult) {
                            if (deleteResult.getStatus().isSuccess()) {
                                appendLog("Successfully deleted data item: " + dataItemUri);
                            } else {
                                appendLog("Failed to delete data item:" + dataItemUri);
                            }
                        }
                    });
        }
    } else {
        Log.e(TAG, "Failed to delete data items"
                 + " - Client disconnected from Google Play Services");
    }
}