Java Code Examples for com.google.android.gms.wearable.DataMap#fromByteArray()

The following examples show how to use com.google.android.gms.wearable.DataMap#fromByteArray() . 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: IncomingRequestWearService.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessageReceived(MessageEvent messageEvent) {
    Log.d(TAG, "onMessageReceived(): " + messageEvent);

    String messagePath = messageEvent.getPath();

    if (messagePath.equals(Constants.MESSAGE_PATH_WEAR)) {
        DataMap dataMap = DataMap.fromByteArray(messageEvent.getData());

        int requestType = dataMap.getInt(Constants.KEY_COMM_TYPE);

        if (requestType == Constants.COMM_TYPE_REQUEST_PROMPT_PERMISSION) {
            promptUserForSensorPermission();

        } else if (requestType == Constants.COMM_TYPE_REQUEST_DATA) {
            respondWithSensorInformation();
        }
    }
}
 
Example 2
Source File: IncomingRequestPhoneService.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onMessageReceived(MessageEvent messageEvent) {
    super.onMessageReceived(messageEvent);
    Log.d(TAG, "onMessageReceived(): " + messageEvent);

    String messagePath = messageEvent.getPath();

    if (messagePath.equals(Constants.MESSAGE_PATH_PHONE)) {

        DataMap dataMap = DataMap.fromByteArray(messageEvent.getData());
        int requestType = dataMap.getInt(Constants.KEY_COMM_TYPE, 0);

        if (requestType == Constants.COMM_TYPE_REQUEST_PROMPT_PERMISSION) {
            promptUserForStoragePermission(messageEvent.getSourceNodeId());

        } else if (requestType == Constants.COMM_TYPE_REQUEST_DATA) {
            respondWithStorageInformation(messageEvent.getSourceNodeId());
        }
    }
}
 
Example 3
Source File: WearableLocationService.java    From android_packages_apps_GmsCore with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessageReceived(MessageEvent messageEvent) {
    if (messageEvent.getPath().equals(PATH_LOCATION_REQUESTS)) {
        DataMap dataMap = DataMap.fromByteArray(messageEvent.getData());
        onLocationRequests(messageEvent.getSourceNodeId(), readLocationRequestList(dataMap, this), dataMap.getBoolean("TRIGGER_UPDATE", false));
    } else if (messageEvent.getPath().equals(PATH_CAPABILITY_QUERY)) {
        onCapabilityQuery(messageEvent.getSourceNodeId());
    }
}
 
Example 4
Source File: DigitalWatchFaceConfigListenerService.java    From wear-os-samples with Apache License 2.0 5 votes vote down vote up
@Override // WearableListenerService
public void onMessageReceived(MessageEvent messageEvent) {

    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "onMessageReceived: " + messageEvent);
    }

    if (!messageEvent.getPath().equals(DigitalWatchFaceUtil.PATH_WITH_FEATURE)) {
        return;
    }
    byte[] rawData = messageEvent.getData();
    // It's allowed that the message carries only some of the keys used in the config DataItem
    // and skips the ones that we don't want to change.
    DataMap configKeysToOverwrite = DataMap.fromByteArray(rawData);
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Received watch face config message: " + configKeysToOverwrite);
    }

    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(Wearable.API).build();
    }
    if (!mGoogleApiClient.isConnected()) {
        ConnectionResult connectionResult =
                mGoogleApiClient.blockingConnect(30, TimeUnit.SECONDS);

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

    DigitalWatchFaceUtil.overwriteKeysInConfigDataMap(mGoogleApiClient, configKeysToOverwrite, null);
}
 
Example 5
Source File: QuizListenerService.java    From AndroidWearable-Samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessageReceived(MessageEvent messageEvent) {
    String path = messageEvent.getPath();
    if (path.equals(QUIZ_EXITED_PATH)) {
        // Remove any lingering question notifications.
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll();
    }
    if (path.equals(QUIZ_ENDED_PATH) || path.equals(QUIZ_EXITED_PATH)) {
        // Quiz ended - display overall results.
        DataMap dataMap = DataMap.fromByteArray(messageEvent.getData());
        int numCorrect = dataMap.getInt(NUM_CORRECT);
        int numIncorrect = dataMap.getInt(NUM_INCORRECT);
        int numSkipped = dataMap.getInt(NUM_SKIPPED);

        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle(getString(R.string.quiz_report))
                .setSmallIcon(R.drawable.ic_launcher)
                .setLocalOnly(true);
        SpannableStringBuilder quizReportText = new SpannableStringBuilder();
        appendColored(quizReportText, String.valueOf(numCorrect), R.color.dark_green);
        quizReportText.append(" " + getString(R.string.correct) + "\n");
        appendColored(quizReportText, String.valueOf(numIncorrect), R.color.dark_red);
        quizReportText.append(" " + getString(R.string.incorrect) + "\n");
        appendColored(quizReportText, String.valueOf(numSkipped), R.color.dark_yellow);
        quizReportText.append(" " + getString(R.string.skipped) + "\n");

        builder.setContentText(quizReportText);
        if (!path.equals(QUIZ_EXITED_PATH)) {
            // Don't add reset option if user exited quiz (there might not be a quiz to reset!).
            builder.addAction(R.drawable.ic_launcher,
                    getString(R.string.reset_quiz), getResetQuizPendingIntent());
        }
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                .notify(QUIZ_REPORT_NOTIF_ID, builder.build());
    }
}
 
Example 6
Source File: QuizListenerService.java    From android-Quiz with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessageReceived(MessageEvent messageEvent) {
    String path = messageEvent.getPath();
    if (path.equals(QUIZ_EXITED_PATH)) {
        // Remove any lingering question notifications.
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll();
    }
    if (path.equals(QUIZ_ENDED_PATH) || path.equals(QUIZ_EXITED_PATH)) {
        // Quiz ended - display overall results.
        DataMap dataMap = DataMap.fromByteArray(messageEvent.getData());
        int numCorrect = dataMap.getInt(NUM_CORRECT);
        int numIncorrect = dataMap.getInt(NUM_INCORRECT);
        int numSkipped = dataMap.getInt(NUM_SKIPPED);

        Notification.Builder builder = new Notification.Builder(this)
                .setContentTitle(getString(R.string.quiz_report))
                .setSmallIcon(R.drawable.ic_launcher)
                .setLocalOnly(true);
        SpannableStringBuilder quizReportText = new SpannableStringBuilder();
        appendColored(quizReportText, String.valueOf(numCorrect), R.color.dark_green);
        quizReportText.append(" " + getString(R.string.correct) + "\n");
        appendColored(quizReportText, String.valueOf(numIncorrect), R.color.dark_red);
        quizReportText.append(" " + getString(R.string.incorrect) + "\n");
        appendColored(quizReportText, String.valueOf(numSkipped), R.color.dark_yellow);
        quizReportText.append(" " + getString(R.string.skipped) + "\n");

        builder.setContentText(quizReportText);
        if (!path.equals(QUIZ_EXITED_PATH)) {
            // Don't add reset option if user exited quiz (there might not be a quiz to reset!).
            builder.addAction(R.drawable.ic_launcher,
                    getString(R.string.reset_quiz), getResetQuizPendingIntent());
        }
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                .notify(QUIZ_REPORT_NOTIF_ID, builder.build());
    }
}
 
Example 7
Source File: WatchFaceConfigListenerService.java    From american-sunsets-watch-face with Apache License 2.0 5 votes vote down vote up
@Override // WearableListenerService
public void onMessageReceived(MessageEvent messageEvent) {
    if (!messageEvent.getPath().equals(SunsetsWatchFaceUtil.PATH_WITH_FEATURE)) {
        return;
    }
    byte[] rawData = messageEvent.getData();
    // It's allowed that the message carries only some of the keys used in the config DataItem
    // and skips the ones that we don't want to change.
    DataMap configKeysToOverwrite = DataMap.fromByteArray(rawData);
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Received watch face config message: " + configKeysToOverwrite);
    }

    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(Wearable.API).build();
    }
    if (!mGoogleApiClient.isConnected()) {
        ConnectionResult connectionResult =
                mGoogleApiClient.blockingConnect(30, TimeUnit.SECONDS);

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

    SunsetsWatchFaceUtil.overwriteKeysInConfigDataMap(mGoogleApiClient, configKeysToOverwrite);
}
 
Example 8
Source File: ExceptionDataListenerService.java    From ExceptionWear with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessageReceived(MessageEvent messageEvent) {
    super.onMessageReceived(messageEvent);
    if(messageEvent.getPath().equals("/exceptionwear/wear_error")) {
        DataMap map = DataMap.fromByteArray(messageEvent.getData());
        readException(map);
    }
}
 
Example 9
Source File: MainActivity.java    From OkWear with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceiveDataApi(DataEventBuffer dataEventBuffer) {
    for (DataEvent event : dataEventBuffer) {
        DataMap dataMap = DataMap.fromByteArray(event.getDataItem().getData());
        final int data = dataMap.getInt(OkWear.DEFAULT_DATA_API_KEY);
        Log.v(TAG, "data: " + data);
    }
}
 
Example 10
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 11
Source File: Message.java    From DronesWear with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int decodeInteractionTypeMessage(DataItem dataItem) {
    int interactionBitfield = InteractionType.NONE;
    if (MESSAGE_TYPE.INTERACTION_TYPE.equals(getMessageType(dataItem))) {
        DataMap dataMap = DataMap.fromByteArray(dataItem.getData());
        interactionBitfield =  dataMap.getInt(VALUE_STR);
    }

    return interactionBitfield;
}
 
Example 12
Source File: Message.java    From DronesWear with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static JoystickData decodeJoystickMessage(DataItem dataItem) {
    JoystickData joystickData = null;
    if (MESSAGE_TYPE.JOYSTICK.equals(getMessageType(dataItem))) {
        DataMap dataMap = DataMap.fromByteArray(dataItem.getData());
        float joystickArray[] = dataMap.getFloatArray(VALUE_STR);
        if (joystickArray != null)
        {
            joystickData = new JoystickData(joystickArray[0], joystickArray[1]);
        }
    }

    return joystickData;
}
 
Example 13
Source File: Message.java    From DronesWear with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static AccelerometerData decodeAcceleroMessage(DataItem dataItem) {
    AccelerometerData accelerometerData = null;
    if (MESSAGE_TYPE.ACC.equals(getMessageType(dataItem))) {
        DataMap dataMap = DataMap.fromByteArray(dataItem.getData());
        float sensordataArray[] = dataMap.getFloatArray(VALUE_STR);
        if (sensordataArray != null)
        {
            accelerometerData = new AccelerometerData(sensordataArray[0], sensordataArray[1], sensordataArray[2]);
        }
    }

    return accelerometerData;
}
 
Example 14
Source File: Persistence.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
@Nullable
public DataMap getDataMap(String key) {
    if (preferences.contains(key)) {
        final String rawB64Data = preferences.getString(key, null);
        byte[] rawData = Base64.decode(rawB64Data, Base64.DEFAULT);
        try {
            return DataMap.fromByteArray(rawData);
        } catch (IllegalArgumentException ex) {
            // Should never happen, and if it happen - we ignore and fallback to null
        }
    }
    return null;
}
 
Example 15
Source File: MainPhoneActivity.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
public void onMessageReceived(MessageEvent messageEvent) {
    Log.d(TAG, "onMessageReceived(): " + messageEvent);

    String messagePath = messageEvent.getPath();

    if (messagePath.equals(Constants.MESSAGE_PATH_PHONE)) {
        DataMap dataMap = DataMap.fromByteArray(messageEvent.getData());

        int commType = dataMap.getInt(Constants.KEY_COMM_TYPE, 0);

        if (commType == Constants.COMM_TYPE_RESPONSE_PERMISSION_REQUIRED) {
            mWearBodySensorsPermissionApproved = false;
            updateWearButtonOnUiThread();

            /* Because our request for remote data requires a remote permission, we now launch
             * a splash activity informing the user we need those permissions (along with
             * other helpful information to approve).
             */
            Intent wearPermissionRationale =
                    new Intent(this, WearPermissionRequestActivity.class);
            startActivityForResult(wearPermissionRationale, REQUEST_WEAR_PERMISSION_RATIONALE);

        } else if (commType == Constants.COMM_TYPE_RESPONSE_USER_APPROVED_PERMISSION) {
            mWearBodySensorsPermissionApproved = true;
            updateWearButtonOnUiThread();
            logToUi("User approved permission on remote device, requesting data again.");
            DataMap outgoingDataRequestDataMap = new DataMap();
            outgoingDataRequestDataMap.putInt(Constants.KEY_COMM_TYPE,
                    Constants.COMM_TYPE_REQUEST_DATA);
            sendMessage(outgoingDataRequestDataMap);

        } else if (commType == Constants.COMM_TYPE_RESPONSE_USER_DENIED_PERMISSION) {
            mWearBodySensorsPermissionApproved = false;
            updateWearButtonOnUiThread();
            logToUi("User denied permission on remote device.");

        } else if (commType == Constants.COMM_TYPE_RESPONSE_DATA) {
            mWearBodySensorsPermissionApproved = true;
            String storageDetails = dataMap.getString(Constants.KEY_PAYLOAD);
            updateWearButtonOnUiThread();
            logToUi(storageDetails);

        } else {
            Log.d(TAG, "Unrecognized communication type received.");
        }
    }
}
 
Example 16
Source File: MainWearActivity.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
public void onMessageReceived(MessageEvent messageEvent) {
    Log.d(TAG, "onMessageReceived(): " + messageEvent);

    String messagePath = messageEvent.getPath();

    if (messagePath.equals(Constants.MESSAGE_PATH_WEAR)) {

        DataMap dataMap = DataMap.fromByteArray(messageEvent.getData());
        int commType = dataMap.getInt(Constants.KEY_COMM_TYPE, 0);

        if (commType == Constants.COMM_TYPE_RESPONSE_PERMISSION_REQUIRED) {
            mPhoneStoragePermissionApproved = false;
            updatePhoneButtonOnUiThread();

            /* Because our request for remote data requires a remote permission, we now launch
             * a splash activity informing the user we need those permissions (along with
             * other helpful information to approve).
             */
            Intent phonePermissionRationaleIntent =
                    new Intent(this, RequestPermissionOnPhoneActivity.class);
            startActivityForResult(phonePermissionRationaleIntent, REQUEST_PHONE_PERMISSION);

        } else if (commType == Constants.COMM_TYPE_RESPONSE_USER_APPROVED_PERMISSION) {
            mPhoneStoragePermissionApproved = true;
            updatePhoneButtonOnUiThread();
            logToUi("User approved permission on remote device, requesting data again.");
            DataMap outgoingDataRequestDataMap = new DataMap();
            outgoingDataRequestDataMap.putInt(Constants.KEY_COMM_TYPE,
                    Constants.COMM_TYPE_REQUEST_DATA);
            sendMessage(outgoingDataRequestDataMap);

        } else if (commType == Constants.COMM_TYPE_RESPONSE_USER_DENIED_PERMISSION) {
            mPhoneStoragePermissionApproved = false;
            updatePhoneButtonOnUiThread();
            logToUi("User denied permission on remote device.");

        } else if (commType == Constants.COMM_TYPE_RESPONSE_DATA) {
            mPhoneStoragePermissionApproved = true;
            String storageDetails = dataMap.getString(Constants.KEY_PAYLOAD);
            updatePhoneButtonOnUiThread();
            logToUi(storageDetails);
        }
    }
}
 
Example 17
Source File: Packager.java    From courier with Apache License 2.0 3 votes vote down vote up
/**
 * In general, this method will only be used by generated code. However, it may be suitable
 * to use this method in some cases (such as in a WearableListenerService).
 *
 * Unpacks the given byte array into an object of the given class.
 *
 * This method will attempt to convert the byte array into a DataMap and then use generated code from
 * the {@link Deliverable} annotation to convert it to an object of the given class.
 *
 * If this is not possible, this method will then attempt to deserialize the byte array
 * using the {@link java.io.Serializable} system.
 *
 * @param context The Context that may be used to load Assets from the data.
 * @param data  The byte array to load the object from.
 * @param targetClass The class of object to unpack.
 * @return An object of the given class.
 */
public static <T> T unpack(Context context, byte[] data, Class<T> targetClass) {
    try {
        final DataMap dataMap = DataMap.fromByteArray(data);
        return unpack(context, dataMap, targetClass);
    }catch (Exception e) {
        return unpackSerializable(data);
    }
}