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

The following examples show how to use com.google.android.gms.wearable.DataMap#putString() . 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: Simulation.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public void Approve(View myview) {
    if (watchkeypad) {
        //Treatments.create(carbs, insulin, thisnotes, new Date().getTime());
        DataMap dataMap = new DataMap();
        dataMap.putDouble("timeoffset", timeoffset);
        dataMap.putDouble("carbs", carbs);
        dataMap.putDouble("insulin", insulin);
        dataMap.putDouble("bloodtest", bloodtest);
        dataMap.putString("notes", thisnotes);
        //dataMap.putLong("timestamp", System.currentTimeMillis());
        ListenerService.createTreatment(dataMap, this);
    }
    else
        SendData(this, WEARABLE_APPROVE_TREATMENT, null);
    finish();
}
 
Example 2
Source File: ExceptionService.java    From ExceptionWear with Apache License 2.0 6 votes vote down vote up
private DataMap createExceptionInformation(Intent intent){

        bos = new ByteArrayOutputStream();
        try {
            oos = new ObjectOutputStream(bos);
            oos.writeObject(intent.getSerializableExtra(EXTRA_EXCEPTION));
        } catch (IOException e) {
            Log.e(WearExceptionTools.EXCEPTION_WEAR_TAG, "createExceptionInformation error while getting exception information.");
        }

        byte[] exceptionData = bos.toByteArray();
        DataMap dataMap = new DataMap();

        // Add a bit of information on the Wear Device to pass a long with the exception
        dataMap.putString("board", Build.BOARD);
        dataMap.putString("fingerprint", Build.FINGERPRINT);
        dataMap.putString("model", Build.MODEL);
        dataMap.putString("manufacturer", Build.MANUFACTURER);
        dataMap.putString("product", Build.PRODUCT);
        dataMap.putString("api_level", Integer.toString(Build.VERSION.SDK_INT));

        dataMap.putByteArray("exception", exceptionData);

        return dataMap;
    }
 
Example 3
Source File: WearableService.java    From sms-ticket with Apache License 2.0 6 votes vote down vote up
private void syncTicketsToWear(String path) {
    Uri uri = Uri.parse(path);
    final ArrayList<DataMap> dataCities = new ArrayList<DataMap>();
    String cityName = uri.getLastPathSegment();

    List<City> cities = CityManager.get(getApplicationContext()).getTicketsInCity(cityName, getApplicationContext());

    for (final City city : cities) {
        final DataMap dataMap = new DataMap();
        dataMap.putLong("id", city.id);
        dataMap.putString("city", city.city);
        dataMap.putString("country", city.country);
        dataMap.putInt("validity", city.validity);
        dataMap.putString("price", city.price);
        dataMap.putString("currency", city.currency);
        dataMap.putString("price_note", city.priceNote);
        dataMap.putString("note", city.note);

        dataCities.add(dataMap);
    }
    PutDataMapRequest data = PutDataMapRequest.createWithAutoAppendedId("/tickets");
    data.getDataMap().putDataMapArrayList("tickets", dataCities);
    syncDataItem(data);
}
 
Example 4
Source File: WatchUpdaterService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private void sendActiveBtDeviceData() {//KS
    if (is_using_bt) {//only required for Collector running on watch
        forceGoogleApiConnect();
        ActiveBluetoothDevice btDevice = ActiveBluetoothDevice.first();
        if (btDevice != null) {
            if (wear_integration) {
                DataMap dataMap = new DataMap();
                Log.d(TAG, "sendActiveBtDeviceData name=" + btDevice.name + " address=" + btDevice.address + " connected=" + btDevice.connected);

                dataMap.putLong("time", new Date().getTime()); // MOST IMPORTANT LINE FOR TIMESTAMP

                dataMap.putString("name", btDevice.name);
                dataMap.putString("address", btDevice.address);
                dataMap.putBoolean("connected", btDevice.connected);

                new SendToDataLayerThread(WEARABLE_ACTIVEBTDEVICE_DATA_PATH, googleApiClient).executeOnExecutor(xdrip.executor, dataMap);
            }
        }
    } else {
        Log.d(TAG, "Not sending activebluetoothdevice data as we are not using bt");
    }
}
 
Example 5
Source File: UtilityService.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Puts a Scene into a DataMap
 *
 * @param scene Scene to convert
 * @return DataMap
 */
private DataMap convertToDataMap(Scene scene) {
    DataMap roomDataMap = new DataMap();

    roomDataMap.putLong(WearableConstants.SCENE_ID_DATAMAP_KEY, scene.getId());
    roomDataMap.putString(WearableConstants.SCENE_NAME_DATAMAP_KEY, scene.getName());

    return roomDataMap;
}
 
Example 6
Source File: UtilityService.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Puts a Receiver into a DataMap
 *
 * @param receiver Receiver to convert
 * @return DataMap
 */
private DataMap convertToDataMap(Receiver receiver) {
    DataMap receiverDataMap = new DataMap();

    receiverDataMap.putLong(WearableConstants.RECEIVER_ID_DATAMAP_KEY, receiver.getId());
    receiverDataMap.putString(WearableConstants.RECEIVER_NAME_DATAMAP_KEY, receiver.getName());
    receiverDataMap.putLong(WearableConstants.RECEIVER_ROOM_ID_DATAMAP_KEY, receiver.getRoomId());
    receiverDataMap.putInt(WearableConstants.RECEIVER_POSITION_IN_ROOM_DATAMAP_KEY, receiver.getPositionInRoom());
    receiverDataMap.putLong(WearableConstants.RECEIVER_LAST_ACTIVATED_BUTTON_ID_DATAMAP_KEY, receiver.getLastActivatedButtonId());

    return receiverDataMap;
}
 
Example 7
Source File: ListenerService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private void sendPrefSettings() {//KS

        Log.d(TAG, "sendPrefSettings enter");
        forceGoogleApiConnect();
        DataMap dataMap = new DataMap();
        boolean enable_wearG5 = mPrefs.getBoolean("enable_wearG5", false);
        boolean force_wearG5 = mPrefs.getBoolean("force_wearG5", false);
        String node_wearG5 = mPrefs.getString("node_wearG5", "");
        String dex_txid = mPrefs.getString("dex_txid", "ABCDEF");
        boolean show_wear_treatments = mPrefs.getBoolean("show_wear_treatments", false);

        if (localnode == null || (localnode != null && localnode.isEmpty())) setLocalNodeName();
        Log.d(TAG, "sendPrefSettings enable_wearG5: " + enable_wearG5 + " force_wearG5:" + force_wearG5 + " node_wearG5:" + node_wearG5 + " localnode:" + localnode + " dex_txid:" + dex_txid + " show_wear_treatments:" + show_wear_treatments);
        dataMap.putLong("time", new Date().getTime()); // MOST IMPORTANT LINE FOR TIMESTAMP
        dataMap.putBoolean("enable_wearG5", enable_wearG5);
        dataMap.putBoolean("force_wearG5", force_wearG5);
        if (force_wearG5) {
            dataMap.putString("node_wearG5", localnode);
        } else {
            if (node_wearG5.equals(localnode)) {
                dataMap.putString("node_wearG5", "");
            } else {
                dataMap.putString("node_wearG5", node_wearG5);
            }
        }
        dataMap.putString("dex_txid", dex_txid);
        dataMap.putInt("bridge_battery", mPrefs.getInt("bridge_battery", -1));//Used in DexCollectionService
        dataMap.putInt("nfc_sensor_age", mPrefs.getInt("nfc_sensor_age", -1));//Used in DexCollectionService for LimiTTer
        dataMap.putBoolean("bg_notifications_watch", mPrefs.getBoolean("bg_notifications", false));
        dataMap.putBoolean("persistent_high_alert_enabled_watch", mPrefs.getBoolean("persistent_high_alert_enabled", false));
        dataMap.putBoolean("show_wear_treatments", show_wear_treatments);
        sendData(WEARABLE_PREF_DATA_PATH, dataMap.toByteArray());

        SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
        if (!node_wearG5.equals(dataMap.getString("node_wearG5", ""))) {
            Log.d(TAG, "sendPrefSettings save to SharedPreferences - node_wearG5:" + dataMap.getString("node_wearG5", ""));
            prefs.putString("node_wearG5", dataMap.getString("node_wearG5", ""));
            prefs.apply();
        }
    }
 
Example 8
Source File: DexCollectionService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static DataMap getWatchStatus() {
    DataMap dataMap = new DataMap();
    dataMap.putString("lastState", lastState);
    if (last_transmitter_Data != null)
        dataMap.putLong("timestamp", last_transmitter_Data.timestamp);
    dataMap.putInt("mStaticState", mStaticState);
    dataMap.putInt("last_battery_level", last_battery_level);
    dataMap.putLong("retry_time", retry_time);
    dataMap.putLong("failover_time", failover_time);
    dataMap.putString("static_last_hexdump", static_last_hexdump);
    dataMap.putString("static_last_sent_hexdump", static_last_sent_hexdump);
    return dataMap;
}
 
Example 9
Source File: BgSendQueue.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static void resendData(Context context, int battery) {//KS
    Log.d("BgSendQueue", "resendData enter battery=" + battery);
    long startTime = new Date().getTime() - (60000 * 60 * 24);
    Intent messageIntent = new Intent();
    messageIntent.setAction(Intent.ACTION_SEND);
    messageIntent.putExtra("message", "ACTION_G5BG");

    BgReading last_bg = BgReading.last();
    if (last_bg != null) {
        Log.d("BgSendQueue", "resendData last_bg.timestamp:" +  JoH.dateTimeText(last_bg.timestamp));
    }

    List<BgReading> graph_bgs = BgReading.latestForGraph(60, startTime);
    BgGraphBuilder bgGraphBuilder = new BgGraphBuilder(context.getApplicationContext());
    if (!graph_bgs.isEmpty()) {
        Log.d("BgSendQueue", "resendData graph_bgs size=" + graph_bgs.size());
        final ArrayList<DataMap> dataMaps = new ArrayList<>(graph_bgs.size());
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
        DataMap entries = dataMap(last_bg, sharedPrefs, bgGraphBuilder, context, battery);
        for (BgReading bg : graph_bgs) {
            dataMaps.add(dataMap(bg, sharedPrefs, bgGraphBuilder, context, battery));
        }
        entries.putDataMapArrayList("entries", dataMaps);
        if (sharedPrefs.getBoolean("extra_status_line", false)) {
            //messageIntent.putExtra("extra_status_line", extraStatusLine(sharedPrefs));
            entries.putString("extra_status_line", extraStatusLine(sharedPrefs));
        }
        Log.d("BgSendQueue", "resendData entries=" + entries);
        messageIntent.putExtra("data", entries.toBundle());

        DataMap stepsDataMap = getSensorSteps(sharedPrefs);
        if (stepsDataMap != null) {
            messageIntent.putExtra("steps", stepsDataMap.toBundle());
        }
        LocalBroadcastManager.getInstance(context).sendBroadcast(messageIntent);
    }
}
 
Example 10
Source File: ListenerService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void sendPersistentStore() {
    if (DexCollectionType.getDexCollectionType().equals(DexCollectionType.DexcomG5)) {
        DataMap dataMap = new DataMap();
        String dex_txid = mPrefs.getString("dex_txid", "ABCDEF");
        dataMap.putByteArray(G5_BATTERY_MARKER, PersistentStore.getBytes(G5_BATTERY_MARKER + dex_txid));
        dataMap.putLong(G5_BATTERY_FROM_MARKER, PersistentStore.getLong(G5_BATTERY_FROM_MARKER + dex_txid));
        dataMap.putString("dex_txid", dex_txid);

        dataMap.putByteArray(G5_FIRMWARE_MARKER, PersistentStore.getBytes(G5_FIRMWARE_MARKER + dex_txid));
        dataMap.putString("dex_txid", dex_txid);
        sendData(WEARABLE_G5BATTERY_PAYLOAD, dataMap.toByteArray());
    }
}
 
Example 11
Source File: ListenerService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public boolean overrideLocale(DataMap dataMap) {
    if (mPrefs.getBoolean("overrideLocale", false)) {
        String localeStr = dataMap.getString("locale", "");
        String locale[] = localeStr.split("_");
        final Locale newLocale = locale == null ? new Locale(localeStr) : locale.length > 1 ? new Locale(locale[0], locale[1]) : new Locale(locale[0]);
        final Locale oldLocale = Locale.getDefault();
        if (newLocale != null && !oldLocale.equals(newLocale)) {
            try {
                Log.d(TAG, "overrideLocale locale from " + oldLocale + " to " + newLocale);
                Context context = getApplicationContext();
                final Resources resources = context.getResources();
                final DisplayMetrics metrics = resources.getDisplayMetrics();
                final Configuration config = resources.getConfiguration();
                config.locale = newLocale;
                resources.updateConfiguration(config, metrics);
                Locale.setDefault(newLocale);
                Log.d(TAG, "overrideLocale default locale " + Locale.getDefault() + " resource locale " + context.getResources().getConfiguration().locale);
                DataMap dm = new DataMap();
                dm.putString("locale", localeStr);
                sendLocalMessage("locale", dm);
                return true;
            } catch (Exception e) {
                Log.e(TAG, "overrideLocale Exception e: " + e);
            }
        }
    }
    return false;
}
 
Example 12
Source File: ListenerService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void sendPersistentStore() {
    if (DexCollectionType.getDexCollectionType().equals(DexCollectionType.DexcomG5)) {
        DataMap dataMap = new DataMap();
        String dex_txid = mPrefs.getString("dex_txid", "ABCDEF");
        dataMap.putByteArray(G5_BATTERY_MARKER, PersistentStore.getBytes(G5_BATTERY_MARKER + dex_txid));
        dataMap.putLong(G5_BATTERY_FROM_MARKER, PersistentStore.getLong(G5_BATTERY_FROM_MARKER + dex_txid));
        dataMap.putString("dex_txid", dex_txid);

        dataMap.putByteArray(G5_FIRMWARE_MARKER, PersistentStore.getBytes(G5_FIRMWARE_MARKER + dex_txid));
        dataMap.putString("dex_txid", dex_txid);
        sendData(WEARABLE_G5BATTERY_PAYLOAD, dataMap.toByteArray());
    }
}
 
Example 13
Source File: RetrieveService.java    From wear-notify-for-reddit with Apache License 2.0 5 votes vote down vote up
private void sendPostsToWearable(@NonNull List<Post> posts, @NonNull final String msg,
                                 @Nullable SimpleArrayMap<String, Asset> assets) {
    if (mGoogleApiClient.isConnected()) {
        // convert to json for sending to watch and to save to shared prefs
        // don't need to preserve the order like having separate String lists, can more easily add/remove fields
        PutDataMapRequest mapRequest = PutDataMapRequest.create(Constants.PATH_REDDIT_POSTS);
        DataMap dataMap = mapRequest.getDataMap();

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

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

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

                    if (dataItemResult.getStatus().isSuccess()) {
                        if (mGoogleApiClient.isConnected()) {
                            mGoogleApiClient.disconnect();
                        }
                    } else {
                        Timber.d("Failed to send posts to wearable " + dataItemResult.getStatus()
                                .getStatusMessage());
                    }
                });
    }
}
 
Example 14
Source File: UtilityService.java    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Puts a Button into a DataMap
 *
 * @param button Button to convert
 * @return DataMap
 */
private DataMap convertToDataMap(Button button) {
    DataMap buttonDataMap = new DataMap();

    buttonDataMap.putLong(WearableConstants.BUTTON_ID_DATAMAP_KEY, button.getId());
    buttonDataMap.putString(WearableConstants.BUTTON_NAME_DATAMAP_KEY, button.getName());
    buttonDataMap.putLong(WearableConstants.BUTTON_RECEIVER_ID_DATAMAP_KEY, button.getReceiverId());

    return buttonDataMap;
}
 
Example 15
Source File: UtilityService.java    From io2015-codelabs with Apache License 2.0 4 votes vote down vote up
/**
 * Transfer the required data over to the wearable
 * @param attractions list of attraction data to transfer over
 */
private void sendDataToWearable(List<Attraction> attractions) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();

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

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

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

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

        Bitmap image = null;
        Bitmap secondaryImage = null;

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

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

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

            DataMap attractionData = new DataMap();

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

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

            attractionsData.add(attractionData);
        }
    }

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

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

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

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

    } else {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
    }
    googleApiClient.disconnect();
}
 
Example 16
Source File: DataBundleUtil.java    From android_external_GmsLib with Apache License 2.0 4 votes vote down vote up
@Override
void store(DataMap dataMap, String key, String value) {
    dataMap.putString(key, value);
}
 
Example 17
Source File: ListenerService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private void sendLocalToast(String msg, int length) {
    DataMap dataMap = new DataMap();
    dataMap.putString("msg", msg);
    dataMap.putInt("length", length);
    sendLocalMessage("msg", dataMap);
}
 
Example 18
Source File: Emmet.java    From Wear-Emmet with Apache License 2.0 4 votes vote down vote up
private void sendDataMap(String path, Object proxy, Method method, Object[] args) throws Throwable {
    final PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(path);

    DataMap datamap = putDataMapRequest.getDataMap();
    datamap.putString("timestamp", new Date().toString());
    datamap.putString(METHOD_NAME, method.getName());

    {
        ArrayList<DataMap> methodDataMapList = new ArrayList<>();

        for (Object argument : args) {
            DataMap map = new DataMap();

            if (argument instanceof Integer) {
                map.putString(PARAM_TYPE, TYPE_INT);
                map.putInt(PARAM_VALUE, (Integer) argument);
            } else if (argument instanceof Float) {
                map.putString(PARAM_TYPE, TYPE_FLOAT);
                map.putFloat(PARAM_VALUE, (Float) argument);
            } else if (argument instanceof Double) {
                map.putString(PARAM_TYPE, TYPE_DOUBLE);
                map.putDouble(PARAM_VALUE, (Double) argument);
            } else if (argument instanceof Long) {
                map.putString(PARAM_TYPE, TYPE_LONG);
                map.putLong(PARAM_VALUE, (Long) argument);
            } else if (argument instanceof String) {
                map.putString(PARAM_TYPE, TYPE_STRING);
                map.putString(PARAM_VALUE, (String) argument);
            } else {
                map.putString(PARAM_TYPE, argument.getClass().getName());
                String encoded = SerialisationUtilsGSON.serialize(argument);
                map.putString(PARAM_VALUE, encoded);
            }

            methodDataMapList.add(map);
        }

        datamap.putDataMapArrayList(METHOD_PARAMS, methodDataMapList);
    }

    if (ENABLE_LOG)
        Log.d(TAG, datamap.toString());

    if (mApiClient != null) {
        if (mApiClient.isConnected()) {
            sendDataMapRequest(putDataMapRequest);
        } else {
            mWaitingDataMapItems.add(putDataMapRequest);
            mApiClient.connect();
        }
    }
}
 
Example 19
Source File: WearableService.java    From sms-ticket with Apache License 2.0 4 votes vote down vote up
private void syncCitiesToWear() {
    CityManager cityManager = CityManager.get(getApplicationContext());
    List<City> cities = cityManager.getUniqueCities(getApplication());
    if (cities.size() > 0) {
        ArrayList<City> orderedCities = new ArrayList<>();
        LocationManager lm = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            City closest = cityManager.getClosest(this, location.getLatitude(), location.getLongitude());
            if (closest != null) {
                orderedCities.add(closest);

                for (int i = 0; i < cities.size(); i++) {
                    if (closest.id != cities.get(i).id) {
                        orderedCities.add(cities.get(i));
                    }
                }
            } else {
                orderedCities.addAll(cities);
            }
        }

        final ArrayList<DataMap> dataCities = new ArrayList<DataMap>();

        for (final City city : orderedCities) {
            final DataMap dataMap = new DataMap();
            dataMap.putLong("id", city.id);
            dataMap.putString("city", city.city);
            dataMap.putString("country", city.country);

            dataCities.add(dataMap);
        }

        if (dataCities.size() == 0) {
            UpdateService.call(getApplicationContext(), false);
            sendError(getResources().getString(R.string.error_zero_cities));
        } else {
            PutDataMapRequest data = PutDataMapRequest.createWithAutoAppendedId("/cities");
            data.getDataMap().putDataMapArrayList("cities", dataCities);
            syncDataItem(data);
        }

    } else {
        UpdateService.call(getApplicationContext(), false);
        sendError(getResources().getString(R.string.error_zero_cities));
    }

}
 
Example 20
Source File: UtilityService.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Transfer the required data over to the wearable
 * @param attractions list of attraction data to transfer over
 */
private void sendDataToWearable(List<Attraction> attractions) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();

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

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

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

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

        Bitmap image = null;
        Bitmap secondaryImage = null;

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

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

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

            DataMap attractionData = new DataMap();

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

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

            attractionsData.add(attractionData);
        }
    }

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

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

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

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

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