Java Code Examples for com.google.android.gms.wearable.DataEventBuffer#close()

The following examples show how to use com.google.android.gms.wearable.DataEventBuffer#close() . 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: HomeListenerService.java    From AndroidWearable-Samples with Apache License 2.0 6 votes vote down vote up
/**
 * Listen for DataItems added/deleted from the geofence service running on the companion.
 */
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "onDataChanged: " + dataEvents + " for " + getPackageName());
    }
    for (DataEvent event : dataEvents) {
        if (event.getType() == DataEvent.TYPE_DELETED) {
            cancelNotificationForDataItem(event.getDataItem());
        } else if (event.getType() == DataEvent.TYPE_CHANGED) {
            // The user has entered a geofence - post a notification!
            String geofenceId = DataMap.fromByteArray(event.getDataItem().getData())
                    .getString(KEY_GEOFENCE_ID);
            postNotificationForGeofenceId(geofenceId, event.getDataItem().getUri());
        }
    }
    dataEvents.close();
}
 
Example 3
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 4
Source File: SoundAlarmListenerService.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "onDataChanged: " + dataEvents + " for " + getPackageName());
    }
    for (DataEvent event : dataEvents) {
        if (event.getType() == DataEvent.TYPE_DELETED) {
            Log.i(TAG, event + " deleted");
        } else if (event.getType() == DataEvent.TYPE_CHANGED) {
            Boolean alarmOn =
                    DataMap.fromByteArray(event.getDataItem().getData()).get(FIELD_ALARM_ON);
            if (alarmOn) {
                mOrigVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);
                mMediaPlayer.reset();
                // Sound alarm at max volume.
                mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, mMaxVolume, 0);
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                try {
                    mMediaPlayer.setDataSource(getApplicationContext(), mAlarmSound);
                    mMediaPlayer.prepare();
                } catch (IOException e) {
                    Log.e(TAG, "Failed to prepare media player to play alarm.", e);
                }
                mMediaPlayer.start();
            } else {
                // Reset the alarm volume to the user's original setting.
                mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, mOrigVolume, 0);
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                }
            }
        }
    }
    dataEvents.close();
}
 
Example 5
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 6
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 7
Source File: HomeListenerService.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "onDataChanged: " + dataEvents + " for " + getPackageName());
    }
    for (DataEvent event : dataEvents) {
        if (event.getType() == DataEvent.TYPE_DELETED) {
            deleteDataItem(event.getDataItem());
        } else if (event.getType() == DataEvent.TYPE_CHANGED) {
            UpdateNotificationForDataItem(event.getDataItem());
        }
    }
    dataEvents.close();
}
 
Example 8
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 9
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 10
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 11
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);
                }
            }
        }
    }