com.google.android.gms.common.data.FreezableUtils Java Examples

The following examples show how to use com.google.android.gms.common.data.FreezableUtils. 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: WearDataLayerListenerService.java    From climb-tracker with Apache License 2.0 6 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    Log.d(TAG, "onDataChanged: " + dataEvents);
    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    dataEvents.close();
    for (DataEvent event : events) {
        Log.d(TAG, "Event: " + event.getDataItem().toString());
        Uri uri = event.getDataItem().getUri();
        String path = uri.getPath();

        if (path.equals(Path.GRADE_SYSTEM)) {
            DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
            String gradeSystem = dataMapItem.getDataMap().getString(Path.GRADE_SYSTEM_KEY);
            if (gradeSystem != null) {
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString(Path.PREF_GRAD_SYSTEM_TYPE, gradeSystem);
                editor.commit();
            }
        }
    }
}
 
Example #2
Source File: ListenerService.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    Log.d(TAG, "onDataChanged: " + dataEvents);

    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);

    for (DataEvent event : events) {
        if (event.getType() == DataEvent.TYPE_CHANGED
                && event.getDataItem() != null
                && Constants.ATTRACTION_PATH.equals(event.getDataItem().getUri().getPath())) {

            DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
            ArrayList<DataMap> attractionsData =
                    dataMapItem.getDataMap().getDataMapArrayList(Constants.EXTRA_ATTRACTIONS);
            showNotification(dataMapItem.getUri(), attractionsData);
        }
    }
}
 
Example #3
Source File: ListenerService.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    Log.d(TAG, "onDataChanged: " + dataEvents);

    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);

    for (DataEvent event : events) {
        if (event.getType() == DataEvent.TYPE_CHANGED
                && event.getDataItem() != null
                && Constants.ATTRACTION_PATH.equals(event.getDataItem().getUri().getPath())) {

            DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
            ArrayList<DataMap> attractionsData =
                    dataMapItem.getDataMap().getDataMapArrayList(Constants.EXTRA_ATTRACTIONS);
            showNotification(dataMapItem.getUri(), attractionsData);
        }
    }
}
 
Example #4
Source File: MainActivity.java    From AndroidWearable-Samples with Apache License 2.0 6 votes vote down vote up
@Override //DataListener
public void onDataChanged(DataEventBuffer dataEvents) {
    LOGD(TAG, "onDataChanged: " + dataEvents);
    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    dataEvents.close();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            for (DataEvent event : events) {
                if (event.getType() == DataEvent.TYPE_CHANGED) {
                    mDataItemListAdapter.add(
                            new Event("DataItem Changed", event.getDataItem().toString()));
                } else if (event.getType() == DataEvent.TYPE_DELETED) {
                    mDataItemListAdapter.add(
                            new Event("DataItem Deleted", event.getDataItem().toString()));
                }
            }
        }
    });
}
 
Example #5
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 #6
Source File: DataLayerListenerService.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    LOGD(TAG, "onDataChanged: " + dataEvents);
    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    dataEvents.close();
    if(!mGoogleApiClient.isConnected()) {
        ConnectionResult connectionResult = mGoogleApiClient
                .blockingConnect(30, TimeUnit.SECONDS);
        if (!connectionResult.isSuccess()) {
            Log.e(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.
    for (DataEvent event : events) {
        Uri uri = event.getDataItem().getUri();
        String path = uri.getPath();
        if (COUNT_PATH.equals(path)) {
            // Get the node id of the node that created the data item from the host portion of
            // the uri.
            String nodeId = uri.getHost();
            // Set the data of the message to be the bytes of the Uri.
            byte[] payload = uri.toString().getBytes();

            // Send the rpc
            Wearable.MessageApi.sendMessage(mGoogleApiClient, nodeId, DATA_ITEM_RECEIVED_PATH,
                    payload);
        }
    }
}
 
Example #7
Source File: MainActivity.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    LOGD(TAG, "onDataChanged(): " + dataEvents);

    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    dataEvents.close();
    for (DataEvent event : events) {
        if (event.getType() == DataEvent.TYPE_CHANGED) {
            String path = event.getDataItem().getUri().getPath();
            if (DataLayerListenerService.IMAGE_PATH.equals(path)) {
                DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
                Asset photo = dataMapItem.getDataMap()
                        .getAsset(DataLayerListenerService.IMAGE_KEY);
                final Bitmap bitmap = loadBitmapFromAsset(mGoogleApiClient, photo);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "Setting background image..");
                        mLayout.setBackground(new BitmapDrawable(getResources(), bitmap));
                    }
                });

            } else if (DataLayerListenerService.COUNT_PATH.equals(path)) {
                LOGD(TAG, "Data Changed for COUNT_PATH");
                generateEvent("DataItem Changed", event.getDataItem().toString());
            } else {
                LOGD(TAG, "Unrecognized path: " + path);
            }

        } else if (event.getType() == DataEvent.TYPE_DELETED) {
            generateEvent("DataItem Deleted", event.getDataItem().toString());
        } else {
            generateEvent("Unknown data event type", "Type = " + event.getType());
        }
    }
}
 
Example #8
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");
    }
}
 
Example #9
Source File: MobileDataLayerListenerService.java    From climb-tracker with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    Log.d(TAG, "onDataChanged: " + dataEvents);
    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    dataEvents.close();

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String gradeSystemType = sharedPref.getString(Path.PREF_GRAD_SYSTEM_TYPE, GradeList.SYSTEM_DEFAULT);

    Location lastLocation = null;

    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        lastLocation  = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    }

    for (DataEvent event : events) {
        Log.d(TAG, "Event: " + event.getDataItem().toString());
        Uri uri = event.getDataItem().getUri();
        String path = uri.getPath();

        if (path.startsWith(Path.CLIMB)) {
            DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
            String routeGradeLabel = dataMapItem.getDataMap().getString(Path.ROUTE_GRADE_LABEL_KEY);
            Date climbDate = new Date(dataMapItem.getDataMap().getLong(Path.CLIMB_DATE_KEY));

            // check that climb date and location date are not too far, do not save location if so.
            double latitude = 0;
            double longitude = 0;
            if(lastLocation != null && Math.abs(lastLocation.getTime() - climbDate.getTime()) < MAX_TIME_FOR_LOCATION) {
                latitude = lastLocation.getLatitude();
                longitude = lastLocation.getLongitude();
            }

            if (routeGradeLabel != null) {
                Log.d(TAG, "New Climb, grade : " + routeGradeLabel + " " + climbDate.toString());

                AuthData authData = mFirebaseRef.getAuth();
                if (authData != null) {
                    Climb newClimb = new Climb(climbDate, routeGradeLabel, gradeSystemType, latitude, longitude);
                    mFirebaseRef.child("users")
                            .child(authData.getUid())
                            .child("climbs")
                            .push().setValue(newClimb);
                }
            }
        }
    }
}
 
Example #10
Source File: QuizListenerService.java    From AndroidWearable-Samples with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    dataEvents.close();

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

    ConnectionResult connectionResult = googleApiClient.blockingConnect(CONNECT_TIMEOUT_MS,
            TimeUnit.MILLISECONDS);
    if (!connectionResult.isSuccess()) {
        Log.e(TAG, "QuizListenerService failed to connect to GoogleApiClient.");
        return;
    }

    for (DataEvent event : events) {
        if (event.getType() == DataEvent.TYPE_CHANGED) {
            DataItem dataItem = event.getDataItem();
            DataMap dataMap = DataMapItem.fromDataItem(dataItem).getDataMap();
            if (dataMap.getBoolean(QUESTION_WAS_ANSWERED)
                    || dataMap.getBoolean(QUESTION_WAS_DELETED)) {
                // Ignore the change in data; it is used in MainActivity to update
                // the question's status (i.e. was the answer right or wrong or left blank).
                continue;
            }
            String question = dataMap.getString(QUESTION);
            int questionIndex = dataMap.getInt(QUESTION_INDEX);
            int questionNum = questionIndex + 1;
            String[] answers = dataMap.getStringArray(ANSWERS);
            int correctAnswerIndex = dataMap.getInt(CORRECT_ANSWER_INDEX);
            Intent deleteOperation = new Intent(this, DeleteQuestionService.class);
            deleteOperation.setData(dataItem.getUri());
            PendingIntent deleteIntent = PendingIntent.getService(this, 0,
                    deleteOperation, PendingIntent.FLAG_UPDATE_CURRENT);
            // First page of notification contains question as Big Text.
            Notification.BigTextStyle bigTextStyle = new Notification.BigTextStyle()
                    .setBigContentTitle(getString(R.string.question, questionNum))
                    .bigText(question);
            Notification.Builder builder = new Notification.Builder(this)
                    .setStyle(bigTextStyle)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setLocalOnly(true)
                    .setDeleteIntent(deleteIntent);

            // Add answers as actions.
            Notification.WearableExtender wearableOptions = new Notification.WearableExtender();
            for (int i = 0; i < answers.length; i++) {
                Notification answerPage = new Notification.Builder(this)
                        .setContentTitle(question)
                        .setContentText(answers[i])
                        .extend(new Notification.WearableExtender()
                                .setContentAction(i))
                        .build();

                boolean correct = (i == correctAnswerIndex);
                Intent updateOperation = new Intent(this, UpdateQuestionService.class);
                // Give each intent a unique action.
                updateOperation.setAction("question_" + questionIndex + "_answer_" + i);
                updateOperation.setData(dataItem.getUri());
                updateOperation.putExtra(UpdateQuestionService.EXTRA_QUESTION_INDEX,
                        questionIndex);
                updateOperation.putExtra(UpdateQuestionService.EXTRA_QUESTION_CORRECT, correct);
                PendingIntent updateIntent = PendingIntent.getService(this, 0, updateOperation,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                Notification.Action action = new Notification.Action.Builder(
                        questionNumToDrawableId.get(i), null, updateIntent)
                        .build();
                wearableOptions.addAction(action).addPage(answerPage);
            }
            builder.extend(wearableOptions);
            Notification notification = builder.build();
            ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                    .notify(questionIndex, notification);
        } else if (event.getType() == DataEvent.TYPE_DELETED) {
            Uri uri = event.getDataItem().getUri();
            // URI's are of the form "/question/0", "/question/1" etc.
            // We use the question index as the notification id.
            int notificationId = Integer.parseInt(uri.getLastPathSegment());
            ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                    .cancel(notificationId);
        }
        // Delete the quiz report, if it exists.
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                .cancel(QUIZ_REPORT_NOTIF_ID);
    }
    googleApiClient.disconnect();
}
 
Example #11
Source File: BinaryWatchFaceConfigListenerService.java    From WearBinaryWatchFace with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    LOGD(TAG, "onDataChanged: " + dataEvents);

    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    dataEvents.close();

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

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

    // Loop through the events and send a message back to the node that created the data item.
    for (DataEvent event : events) {
        Uri uri = event.getDataItem().getUri();
        String path = uri.getPath();

        DataMapItem item = DataMapItem.fromDataItem(event.getDataItem());

        switch (path) {
            case CommonConstants.DATA_PATH_DOT_COLOR:
                putIntPreference(KEY_DOT_COLOR, item.getDataMap().getInt(CommonConstants.DATA_VALUE));
                break;

            case CommonConstants.DATA_PATH_BACKGROUND_COLOR:
                putIntPreference(KEY_BACKGROUND_COLOR, item.getDataMap().getInt(CommonConstants.DATA_VALUE));
                break;

            case CommonConstants.DATA_PATH_DOT_COLOR_RESET:
                removePreference(KEY_DOT_COLOR);
                break;

            case CommonConstants.DATA_PATH_BACKGROUND_COLOR_RESET:
                removePreference(KEY_BACKGROUND_COLOR);
                break;

            case CommonConstants.DATA_PATH_CHANGE_LAYOUT:
                putIntPreference(KEY_LAYOUT, item.getDataMap().getInt(CommonConstants.DATA_VALUE, CommonConstants.PREFS_LAYOUT_VERTICAL));
                break;

            case CommonConstants.DATA_PATH_SHOW_DIGITAL_TIME:
                putBooleanPreference(KEY_SHOW_DIGITAL_TIME, item.getDataMap().getBoolean(CommonConstants.DATA_VALUE, false));
        }

        getBaseContext().sendBroadcast(new Intent(Constants.NEW_CONFIGURATION_RECEIVED));

    }
}
 
Example #12
Source File: OngoingNotificationListenerService.java    From WearOngoingNotificationSample with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
    public void onDataChanged(DataEventBuffer dataEvents) {
        final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
        dataEvents.close();

        if (!mGoogleApiClient.isConnected()) {
            ConnectionResult connectionResult = mGoogleApiClient
                    .blockingConnect(30, TimeUnit.SECONDS);
            if (!connectionResult.isSuccess()) {
                Log.e(TAG, "Service failed to connect to GoogleApiClient.");
                return;
            }
        }

        for (DataEvent event : events) {
            if (event.getType() == DataEvent.TYPE_CHANGED) {
                String path = event.getDataItem().getUri().getPath();
                if (Constants.PATH_NOTIFICATION.equals(path)) {
                    // Get the data out of the event
                    DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
                    final String title = dataMapItem.getDataMap().getString(Constants.KEY_TITLE);
                    Asset asset = dataMapItem.getDataMap().getAsset(Constants.KEY_IMAGE);

                    // Build the intent to display our custom notification
                    Intent notificationIntent = new Intent(this, NotificationActivity.class);
                    notificationIntent.putExtra(NotificationActivity.EXTRA_TITLE, title);
                    notificationIntent.putExtra(NotificationActivity.EXTRA_IMAGE, asset);
                    PendingIntent notificationPendingIntent = PendingIntent.getActivity(
                            this,
                            0,
                            notificationIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT);

                    // Create the ongoing notification

                    // Use this for multipage notifications
//                    Notification secondPageNotification =
//                            new Notification.Builder(this)
//                                    .extend(new Notification.WearableExtender()
//                                            .setDisplayIntent(notificationPendingIntent))
//                                    .build();

                    Notification.Builder notificationBuilder =
                            new Notification.Builder(this)
                                    .setSmallIcon(R.drawable.ic_launcher)
                                    .extend(new Notification.WearableExtender()
                                            .setDisplayIntent(notificationPendingIntent)
//                                            .addPage(secondPageNotification)
                                    );

                    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                            .notify(NOTIFICATION_ID, notificationBuilder.build());
                } else {
                    Log.d(TAG, "Unrecognized path: " + path);
                }
            }
        }
    }