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

The following examples show how to use com.google.android.gms.wearable.DataMap#getString() . 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: ListenerService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private void syncSensorData(DataMap dataMap, Context context) {//KS
    Log.d(TAG, "syncSensorData");
    if (dataMap != null) {
        String uuid = dataMap.getString("uuid");
        Log.d(TAG, "syncSensorData add Sensor for uuid=" + uuid);
        long started_at = dataMap.getLong("started_at");
        Integer latest_battery_level = dataMap.getInt("latest_battery_level");
        String sensor_location = dataMap.getString("sensor_location");
        Sensor.InitDb(context);//ensure database has already been initialized
        if (uuid != null && !uuid.isEmpty()) {
            Log.d(TAG, "syncSensorData add Sensor for uuid=" + uuid + " timestamp=" + started_at + " timeString=" +  JoH.dateTimeText(started_at));
            Sensor sensor = Sensor.getByUuid(uuid);
            if (sensor == null) {
                Log.d(TAG, "syncSensorData createUpdate new Sensor...");
                Sensor.createUpdate(started_at, 0, latest_battery_level, sensor_location, uuid);
                Sensor newsensor = Sensor.currentSensor();
                if (newsensor != null) {
                    Log.d(TAG, "syncSensorData createUpdate Sensor with uuid=" + uuid + " started at=" + started_at);
                } else
                    Log.d(TAG, "syncSensorData Failed to createUpdate new Sensor for uuid=" + uuid);
            } else
                Log.d(TAG, "syncSensorData Sensor already exists with uuid=" + uuid);
        }
    }
}
 
Example 2
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 3
Source File: ListenerService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private void syncActiveBtDeviceData(DataMap dataMap, Context context) {//KS
    Log.d(TAG, "syncActiveBtDeviceData");
    if (dataMap != null) {
        String name = dataMap.getString("name", "");
        String address = dataMap.getString("address", "");
        Boolean connected = dataMap.getBoolean("connected", false);
        Log.d(TAG, "syncActiveBtDeviceData add ActiveBluetoothDevice for name=" + name + " address=" + address + " connected=" + connected);
        Sensor.InitDb(context);//ensure database has already been initialized
        if (name != null && !name.isEmpty() && address != null && !address.isEmpty()) {
            final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            synchronized (ActiveBluetoothDevice.table_lock) {
                ActiveBluetoothDevice btDevice = new Select().from(ActiveBluetoothDevice.class)
                        .orderBy("_ID desc")
                        .executeSingle();

                prefs.edit().putString("last_connected_device_address", address).apply();
                if (btDevice == null) {
                    ActiveBluetoothDevice newBtDevice = new ActiveBluetoothDevice();
                    newBtDevice.name = name;
                    newBtDevice.address = address;
                    newBtDevice.connected = connected;
                    newBtDevice.save();
                } else {
                    btDevice.name = name;
                    btDevice.address = address;
                    btDevice.connected = connected;
                    btDevice.save();
                }
            }
        }
    }
}
 
Example 4
Source File: WatchUpdaterService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void syncStepSensorData(DataMap dataMap, boolean bBenchmark) {
    Log.d(TAG, "syncStepSensorData");

    ArrayList<DataMap> entries = dataMap.getDataMapArrayList("entries");
    long timeOfLastEntry = 0;
    Log.d(TAG, "syncStepSensorData add to Table");
    if (entries != null) {

        Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .registerTypeAdapter(Date.class, new DateTypeAdapter())
                .serializeSpecialFloatingPointValues()
                .create();

        StepCounter pm = StepCounter.last();
        Log.d(TAG, "syncStepSensorData add Table entries count=" + entries.size());
        for (DataMap entry : entries) {
            if (entry != null) {
                Log.d(TAG, "syncStepSensorData add Table entry=" + entry);
                String record = entry.getString("entry");
                if (record != null) {
                    Log.d(TAG, "syncStepSensorData add Table record=" + record);
                    StepCounter data = gson.fromJson(record, StepCounter.class);
                    if (data != null) {
                        timeOfLastEntry = (long) data.timestamp + 1;
                        Log.d(TAG, "syncStepSensorData add Entry Wear=" + data.toString());
                        Log.d(TAG, "syncStepSensorData WATCH data.metric=" + data.metric + " timestamp=" + JoH.dateTimeText((long) data.timestamp));
                        if (!bBenchmark)
                            data.saveit();
                    }
                }
            }
        }
        sendDataReceived(DATA_ITEM_RECEIVED_PATH, "DATA_RECEIVED_LOGS count=" + entries.size(), timeOfLastEntry, bBenchmark ? "BM" : "STEP", -1);
    }
}
 
Example 5
Source File: BaseWatchFace.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    DataMap dataMap = DataMap.fromBundle(intent.getBundleExtra("data"));
    if (layoutSet) {
        wakeLock.acquire(50);
        sgvLevel = dataMap.getLong("sgvLevel");
        batteryLevel = dataMap.getInt("batteryLevel");
        datetime = dataMap.getDouble("timestamp");
        rawString = dataMap.getString("rawString");
        sgvString = dataMap.getString("sgvString");
        batteryString = dataMap.getString("battery");
        mSgv.setText(dataMap.getString("sgvString"));

        if(ageLevel()<=0) {
            mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
        }

        final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(BaseWatchFace.this);
        mTime.setText(timeFormat.format(System.currentTimeMillis()));

        showAgoRawBatt();

        mDirection.setText(dataMap.getString("slopeArrow"));
        mDelta.setText(dataMap.getString("delta"));

        if (chart != null) {
            addToWatchSet(dataMap);
            setupCharts();
        }
        mRelativeLayout.measure(specW, specH);
        mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(),
                mRelativeLayout.getMeasuredHeight());
        invalidate();
    } else {
        Log.d("ERROR: ", "DATA IS NOT YET SET");
    }
    setColor();
}
 
Example 6
Source File: WearableLocationService.java    From android_packages_apps_GmsCore with Apache License 2.0 5 votes vote down vote up
private static LocationRequestInternal readLocationRequest(DataMap dataMap, Context context) {
    LocationRequestInternal request = new LocationRequestInternal();
    request.triggerUpdate = true;
    request.request = new LocationRequest();
    request.clients = Collections.emptyList();

    if (dataMap.containsKey("PRIORITY"))
        request.request.setPriority(dataMap.getInt("PRIORITY", 0));
    if (dataMap.containsKey("INTERVAL_MS"))
        request.request.setInterval(dataMap.getLong("INTERVAL_MS", 0));
    if (dataMap.containsKey("FASTEST_INTERVAL_MS"))
        request.request.setFastestInterval(dataMap.getLong("FASTEST_INTERVAL_MS", 0));
    //if (dataMap.containsKey("MAX_WAIT_TIME_MS"))
    if (dataMap.containsKey("SMALLEST_DISPLACEMENT_METERS"))
        request.request.setSmallestDisplacement(dataMap.getFloat("SMALLEST_DISPLACEMENT_METERS", 0));
    if (dataMap.containsKey("NUM_UPDATES"))
        request.request.setNumUpdates(dataMap.getInt("NUM_UPDATES", 0));
    if (dataMap.containsKey("EXPIRATION_DURATION_MS"))
        request.request.setExpirationDuration(dataMap.getLong("EXPIRATION_DURATION_MS", 0));
    if (dataMap.containsKey("TAG"))
        request.tag = dataMap.getString("TAG");
    if (dataMap.containsKey("CLIENTS_PACKAGE_ARRAY")) {
        String[] packages = dataMap.getStringArray("CLIENTS_PACKAGE_ARRAY");
        if (packages != null) {
            request.clients = new ArrayList<ClientIdentity>();
            for (String packageName : packages) {
                request.clients.add(generateClientIdentity(packageName, context));
            }
        }
    }

    return request;
}
 
Example 7
Source File: DexCollectionService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static void setWatchStatus(DataMap dataMap) {
    lastStateWatch = dataMap.getString("lastState", "");
    last_transmitter_DataWatch = new TransmitterData();
    last_transmitter_DataWatch.timestamp = dataMap.getLong("timestamp", 0);
    mStaticStateWatch = dataMap.getInt("mStaticState", 0);
    last_battery_level_watch = dataMap.getInt("last_battery_level", -1);
    retry_time_watch = dataMap.getLong("retry_time", 0);
    failover_time_watch = dataMap.getLong("failover_time", 0);
    static_last_hexdump_watch = dataMap.getString("static_last_hexdump", "");
    static_last_sent_hexdump_watch = dataMap.getString("static_last_sent_hexdump", "");
}
 
Example 8
Source File: ListenerService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
private void syncAlertTypeData(DataMap dataMap, Context context) {//KS
    Log.d(TAG, "syncAlertTypeData");

    ArrayList<DataMap> entries = dataMap.getDataMapArrayList("entries");
    if (entries != null) {

        Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .registerTypeAdapter(Date.class, new DateTypeAdapter())
                .serializeSpecialFloatingPointValues()
                .create();

        Log.d(TAG, "syncAlertTypeData add AlertType Table entries count=" + entries.size());
        Sensor.InitDb(context);//ensure database has already been initialized
        AlertType.remove_all();
        for (DataMap entry : entries) {
            if (entry != null) {
                String alertrecord = entry.getString("alert");
                if (alertrecord != null) {
                    AlertType data = gson.fromJson(alertrecord, AlertType.class);
                    AlertType exists = AlertType.get_alert(data.uuid);
                    if (exists != null) {
                        Log.d(TAG, "syncAlertTypeData AlertType exists for uuid=" + data.uuid + " name=" + data.name);
                        exists.name = data.name;
                        exists.active = data.active;
                        exists.volume = data.volume;
                        exists.vibrate = data.vibrate;
                        exists.light = data.light;
                        exists.override_silent_mode = data.override_silent_mode;
                        exists.predictive = data.predictive;
                        exists.time_until_threshold_crossed = data.time_until_threshold_crossed;
                        exists.above= data.above;
                        exists.threshold = data.threshold;
                        exists.all_day = data.all_day;
                        exists.start_time_minutes = data.start_time_minutes;
                        exists.end_time_minutes = data.end_time_minutes;
                        exists.minutes_between = data.minutes_between;
                        exists.default_snooze = data.default_snooze;
                        exists.text = data.text;
                        exists.mp3_file = data.mp3_file;
                        exists.save();
                    }
                    else {
                        data.save();
                        Log.d(TAG, "syncAlertTypeData AlertType does not exist for uuid=" + data.uuid);
                    }
                    exists = AlertType.get_alert(data.uuid);
                    if (exists != null)
                        Log.d(TAG, "syncAlertTypeData AlertType GSON saved BG: " + exists.toS());
                    else
                        Log.d(TAG, "syncAlertTypeData AlertType GSON NOT saved");
                }
            }
        }
    }
}
 
Example 9
Source File: WatchUpdaterService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void syncBgReadingsData(DataMap dataMap) {
    Log.d(TAG, "sync-precalculated-bg-readings-Data");

    final int calibration_state = dataMap.getInt("native_calibration_state", 0);
    Ob1G5CollectionService.processCalibrationState(CalibrationState.parse(calibration_state));
    Ob1G5StateMachine.injectDexTime(dataMap.getString("dextime", null));

    final boolean queue_drained = dataMap.getBoolean(PREF_QUEUE_DRAINED);
    if (queue_drained) {
        Ob1G5StateMachine.emptyQueue();
    }


    final ArrayList<DataMap> entries = dataMap.getDataMapArrayList("entries");
    if (entries != null) {
        final Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .registerTypeAdapter(Date.class, new DateTypeAdapter())
                .serializeSpecialFloatingPointValues()
                .create();


        final int count = entries.size();

        if (count > 0) {

            final Sensor current_sensor = Sensor.currentSensor();
            if (current_sensor == null) {
                UserError.Log.e(TAG, "Cannot sync wear BG readings because sensor is marked stopped on phone");
                return;
            }

            Log.d(TAG, "syncTransmitterData add BgReading Table entries count=" + count);
            int idx = 0;
            long timeOfLastBG = 0;
            for (DataMap entry : entries) {
                if (entry != null) {
                    idx++;
                    final String bgrecord = entry.getString("bgs");
                    if (bgrecord != null) {

                        final BgReading bgData = gson.fromJson(bgrecord, BgReading.class);

                        final BgReading uuidexists = BgReading.findByUuid(bgData.uuid);
                        if (uuidexists == null) {

                            final BgReading exists = BgReading.getForTimestamp(bgData.timestamp);
                            if (exists == null) {
                                Log.d(TAG, "Saving new synced pre-calculated bg-reading: " + JoH.dateTimeText(bgData.timestamp) + " last entry: " + (idx == count) + " " + BgGraphBuilder.unitized_string_static(bgData.calculated_value));
                                bgData.sensor = current_sensor;
                                bgData.save();
                                BgSendQueue.handleNewBgReading(bgData, "create", xdrip.getAppContext(), Home.get_follower(), idx != count);
                            } else {
                                Log.d(TAG, "BgReading for timestamp already exists: " + JoH.dateTimeText(bgData.timestamp));
                            }
                        } else {
                            Log.d(TAG, "BgReading with uuid: " + bgData.uuid + " already exists: " + JoH.dateTimeText(bgData.timestamp));
                        }

                        timeOfLastBG = Math.max(bgData.timestamp + 1, timeOfLastBG);
                    }
                }
            }
            sendDataReceived(DATA_ITEM_RECEIVED_PATH, "DATA_RECEIVED_BGS count=" + entries.size(), timeOfLastBG, "BG", -1);

        } else {
            UserError.Log.e(TAG, "Not acknowledging wear BG readings as count was 0");
        }
    } else {
        UserError.Log.d(TAG, "Null entries list - should only happen with native status update only");
    }
}
 
Example 10
Source File: G5BaseService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static void setWatchStatus(DataMap dataMap) {
    lastStateWatch = dataMap.getString("lastState", "");
    static_last_timestamp_watch = dataMap.getLong("timestamp", 0);
}
 
Example 11
Source File: Command.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
Command(final DataMap dataMap) {
	icon = Icon.values()[dataMap.getInt(Constants.UART.Configuration.Command.ICON_ID)];
	command = dataMap.getString(Constants.UART.Configuration.Command.MESSAGE);
	eol = Eol.values()[dataMap.getInt(Constants.UART.Configuration.Command.EOL)];
}
 
Example 12
Source File: CircleWatchface.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    final PowerManager.WakeLock wl = JoH.getWakeLock("circle-message-receiver", 60000);
    try {
        DataMap dataMap;
        Bundle bundle = intent.getBundleExtra("msg");
        if (bundle != null) {
            dataMap = DataMap.fromBundle(bundle);
            String msg = dataMap.getString("msg", "");
            int length = dataMap.getInt("length", 0);
            JoH.static_toast(xdrip.getAppContext(), msg, length);
        }
        bundle = intent.getBundleExtra("steps");
        if (bundle != null) {
            dataMap = DataMap.fromBundle(bundle);
            if (mTimeStepsRcvd <= dataMap.getLong("steps_timestamp", 0)) {
                mStepsCount = dataMap.getInt("steps", 0);
                mTimeStepsRcvd = dataMap.getLong("steps_timestamp", 0);
            }
        }
        bundle = intent.getBundleExtra("data");
        if (bundle != null) {
            dataMap = DataMap.fromBundle(bundle);
            setSgvLevel((int) dataMap.getLong("sgvLevel"));
            Log.d(TAG, "CircleWatchface sgv level : " + getSgvLevel());
            setSgvString(dataMap.getString("sgvString"));
            Log.d(TAG, "CircleWatchface sgv string : " + getSgvString());
            setRawString(dataMap.getString("rawString"));
            setDelta(dataMap.getString("delta"));
            setDatetime(dataMap.getDouble("timestamp"));
            mExtraStatusLine = dataMap.getString("extra_status_line");
            addToWatchSet(dataMap);


            //start animation?
            // dataMap.getDataMapArrayList("entries") == null -> not on "resend data".
            if (sharedPrefs.getBoolean("animation", false) && dataMap.getDataMapArrayList("entries") == null && (getSgvString().equals("100") || getSgvString().equals("5.5") || getSgvString().equals("5,5"))) {
                startAnimation();
            }

            prepareLayout();
            prepareDrawTime();
            invalidate();
        }
        //status
        bundle = intent.getBundleExtra("status");
        if (bundle != null) {
            dataMap = DataMap.fromBundle(bundle);
            setStatusString(dataMap.getString("externalStatusString"));

            prepareLayout();
            prepareDrawTime();
            invalidate();
        }
    } finally {
        JoH.releaseWakeLock(wl);
    }
}
 
Example 13
Source File: ListenerService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void syncTreatmentsData(DataMap dataMap, Context context) {
    Log.d(TAG, "syncTreatmentsData");

    boolean changed = false;
    String action = dataMap.getString("action");
    if (action.equals("delete")) {
        Log.d(TAG, "syncTreatmentsData Delete Treatments");
        deleteTreatment(dataMap);
        showTreatments(context, "treats");
    }
    else {
        ArrayList<DataMap> entries = dataMap.getDataMapArrayList("entries");
        if (entries != null) {
            Gson gson = new GsonBuilder()
                        .excludeFieldsWithoutExposeAnnotation()
                        .registerTypeAdapter(Date.class, new DateTypeAdapter())
                        .serializeSpecialFloatingPointValues()
                        .create();
            Log.d(TAG, "syncTreatmentsData add Treatments Table entries count=" + entries.size());
            Sensor.InitDb(context);//ensure database has already been initialized
            for (DataMap entry : entries) {
                if (entry != null) {
                    String record = entry.getString("data");
                    if (record != null) {
                        Treatments data = gson.fromJson(record, Treatments.class);
                        Treatments exists = Treatments.byuuid(data.uuid);
                        if (exists != null) {
                            Log.d(TAG, "syncTreatmentsData save existing Treatments for action insert uuid=" + data.uuid + " timestamp=" + data.timestamp + " timeString=" + JoH.dateTimeText(data.timestamp) + " carbs=" + data.carbs + " insulin=" + data.insulin + " exists.systime=" + JoH.dateTimeText(exists.systimestamp));
                            if (exists.timestamp != data.timestamp) {//currently only tracking timestamp on watch
                                changed = true;
                            }
                            exists.enteredBy = data.enteredBy;
                            exists.eventType = data.eventType;
                            exists.insulin = data.insulin;
                            exists.carbs = data.carbs;
                            exists.created_at = data.created_at;
                            exists.notes = data.notes;
                            exists.timestamp = data.timestamp;
                            exists.systimestamp = exists.systimestamp > 0 ? exists.systimestamp : data.timestamp < last_send_previous_treatments ? data.timestamp : last_send_previous_treatments > 0 ? last_send_previous_treatments - 1 : JoH.tsl();
                            exists.save();
                        } else {
                            changed = true;
                            data.systimestamp = data.timestamp < last_send_previous_treatments ? data.timestamp : last_send_previous_treatments > 0 ? last_send_previous_treatments - 1 : JoH.tsl();
                            data.save();
                            Log.d(TAG, "syncTreatmentsData create new treatment for action insert uuid=" + data.uuid + " timestamp=" + data.timestamp + " timeString=" + JoH.dateTimeText(data.timestamp) + " carbs=" + data.carbs + " insulin=" + data.insulin + " systime=" + JoH.dateTimeText(data.systimestamp));
                        }
                    }
                }
            }
            if (changed) {
                showTreatments(context, "treats");
            }
        }
    }
}
 
Example 14
Source File: QuizListenerService.java    From android-Quiz with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    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 : dataEvents) {
        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 15
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 16
Source File: ListenerService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void syncCalibrationData(DataMap dataMap, Context context) {//KS
    Log.d(TAG, "syncCalibrationData");

    boolean changed = false;
    ArrayList<DataMap> entries = dataMap.getDataMapArrayList("entries");
    if (entries != null) {

        Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .registerTypeAdapter(Date.class, new DateTypeAdapter())
                .serializeSpecialFloatingPointValues()
                .create();

        Log.d(TAG, "syncCalibrationData add Calibration Table entries count=" + entries.size());
        Sensor.InitDb(context);//ensure database has already been initialized
        Sensor sensor = Sensor.currentSensor();
        if (sensor != null) {
            for (DataMap entry : entries) {
                if (entry != null) {
                    String calibration = entry.getString("bgs"); // bgs should be refactored to avoid confusion
                    if (calibration != null) {
                        Calibration bgData = gson.fromJson(calibration, Calibration.class);
                        Calibration exists = Calibration.findByUuid(bgData.uuid);
                        bgData.sensor = sensor;
                        if (exists != null) {
                            Log.d(TAG, "syncCalibrationData Calibration exists for uuid=" + bgData.uuid + " bg=" + bgData.bg + " timestamp=" + bgData.timestamp + " timeString=" +  JoH.dateTimeText(bgData.timestamp));
                            if (exists.slope != bgData.slope || exists.slope_confidence != bgData.slope_confidence || exists.timestamp != bgData.timestamp || exists.bg != bgData.bg) {//slope* indicates if shown on graph
                                changed = true;
                            }
                            exists.adjusted_raw_value = bgData.adjusted_raw_value;
                            exists.bg = bgData.bg;
                            exists.check_in = bgData.check_in;
                            exists.distance_from_estimate = bgData.distance_from_estimate;
                            exists.estimate_bg_at_time_of_calibration = bgData.estimate_bg_at_time_of_calibration;
                            exists.estimate_raw_at_time_of_calibration = bgData.estimate_raw_at_time_of_calibration;
                            exists.first_decay = bgData.first_decay;
                            exists.first_intercept = bgData.first_intercept;
                            exists.first_scale = bgData.first_scale;
                            exists.first_slope = bgData.first_slope;
                            exists.intercept = bgData.intercept;
                            exists.possible_bad = bgData.possible_bad;
                            exists.raw_timestamp = bgData.raw_timestamp;
                            exists.raw_value = bgData.raw_value;
                            exists.second_decay = bgData.second_decay;
                            exists.second_intercept = bgData.second_intercept;
                            exists.second_scale = bgData.second_scale;
                            exists.second_slope = bgData.second_slope;
                            exists.sensor = sensor;
                            exists.sensor_age_at_time_of_estimation = bgData.sensor_age_at_time_of_estimation;
                            exists.sensor_confidence = bgData.sensor_confidence;
                            exists.sensor_uuid = bgData.sensor_uuid;
                            exists.slope = bgData.slope;
                            exists.slope_confidence = bgData.slope_confidence;
                            exists.timestamp = bgData.timestamp;
                            exists.save();
                        }
                        else {
                            changed = true;
                            bgData.save();
                            //final boolean adjustPast = mPrefs.getBoolean("rewrite_history", true);
                            Log.d(TAG, "syncCalibrationData Calibration does not exist for uuid=" + bgData.uuid + " timestamp=" + bgData.timestamp + " timeString=" +  JoH.dateTimeText(bgData.timestamp));
                            //Calibration.adjustRecentBgReadings(adjustPast ? 30 : 2);
                        }
                        exists = Calibration.findByUuid(bgData.uuid);
                        if (exists != null)
                            Log.d(TAG, "syncCalibrationData Calibration GSON saved BG: " + exists.toS());
                        else
                            Log.d(TAG, "syncCalibrationData Calibration GSON NOT saved");
                    }
                }
            }
        }
        else {
            Log.d(TAG, "syncCalibrationData No Active Sensor!! Request WEARABLE_INITDB_PATH");
            sendData(WEARABLE_INITDB_PATH, null);
        }
        if (changed) {
            showTreatments(context, "cals");
        }
    }
}
 
Example 17
Source File: WatchUpdaterService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private synchronized void syncTransmitterData(DataMap dataMap, boolean bBenchmark) {//KS
    Log.d(TAG, "syncTransmitterData");

    ArrayList<DataMap> entries = dataMap.getDataMapArrayList("entries");
    long timeOfLastBG = 0;
    Log.d(TAG, "syncTransmitterData add BgReading Table");
    if (entries != null) {

        Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .registerTypeAdapter(Date.class, new DateTypeAdapter())
                .serializeSpecialFloatingPointValues()
                .create();

        int idx = 0;
        int count = entries.size();
        Log.d(TAG, "syncTransmitterData add BgReading Table entries count=" + count);
        for (DataMap entry : entries) {
            if (entry != null) {
                //Log.d(TAG, "syncTransmitterData add BgReading Table entry=" + entry);
                idx++;
                String bgrecord = entry.getString("bgs");
                if (bgrecord != null) {//for (TransmitterData bgData : bgs) {
                    //Log.d(TAG, "syncTransmitterData add TransmitterData Table bgrecord=" + bgrecord);
                    TransmitterData bgData = gson.fromJson(bgrecord, TransmitterData.class);
                    //TransmitterData bgData = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(bgrecord, TransmitterData.class);
                    TransmitterData exists = TransmitterData.getForTimestamp(bgData.timestamp);
                    TransmitterData uuidexists = TransmitterData.findByUuid(bgData.uuid);
                    timeOfLastBG = bgData.timestamp + 1;
                    if (exists != null || uuidexists != null) {
                        Log.d(TAG, "syncTransmitterData BG already exists for uuid=" + bgData.uuid + " timestamp=" + bgData.timestamp + " timeString=" + JoH.dateTimeText(bgData.timestamp) + " raw_data=" + bgData.raw_data);
                    } else {
                        Log.d(TAG, "syncTransmitterData add BG; does NOT exist for uuid=" + bgData.uuid + " timestamp=" + bgData.timestamp + " timeString=" + JoH.dateTimeText(bgData.timestamp) + " raw_data=" + bgData.raw_data);
                        if (!bBenchmark) {
                            bgData.save();

                            //Check
                            if (TransmitterData.findByUuid(bgData.uuid) != null)
                                Log.d(TAG, "syncTransmitterData: TransmitterData was saved for uuid:" + bgData.uuid);
                            else {
                                Log.e(TAG, "syncTransmitterData: TransmitterData was NOT saved for uuid:" + bgData.uuid);
                                return;
                            }

                            //KS the following is from G5CollectionService processNewTransmitterData()
                            Sensor sensor = Sensor.currentSensor();
                            if (sensor == null) {
                                Log.e(TAG, "syncTransmitterData: No Active Sensor, Data only stored in Transmitter Data");
                                return;
                            }
                            //TODO : LOG if unfiltered or filtered values are zero
                            Sensor.updateBatteryLevel(sensor, bgData.sensor_battery_level);
                            Log.i(TAG, "syncTransmitterData: BG timestamp create " + Long.toString(bgData.timestamp));//android.util.Log.i
                            BgReading bgExists;

                            //KS TODO wear implements limited alerts, therefore continue to process all alerts on phone for last entry
                            if (count > 1 && idx < count) {
                                bgExists = BgReading.create(bgData.raw_data, bgData.filtered_data, this, bgData.timestamp, true);//Disable Notifications for bulk insert
                            } else {
                                bgExists = BgReading.create(bgData.raw_data, bgData.filtered_data, this, bgData.timestamp);
                            }
                            if (bgExists != null)
                                Log.d(TAG, "syncTransmitterData BG GSON saved BG: " + bgExists.toS());
                            else
                                Log.e(TAG, "syncTransmitterData BG GSON NOT saved");
                        }
                    }
                }
            }
        }
        sendDataReceived(DATA_ITEM_RECEIVED_PATH, "DATA_RECEIVED_BGS count=" + entries.size(), timeOfLastBG, bBenchmark ? "BM" : "BG", -1);
    }
}
 
Example 18
Source File: Settings.java    From PixelWatchFace with GNU General Public License v3.0 4 votes vote down vote up
public ArrayList<UpdatesRequired> updateSettings(
    DataMap dataMap) {  // returns if weather update required
  String TAG = "updateSettings";
  boolean tempShowTemperature = showTemperature;
  boolean tempShowWeatherIcon = showWeatherIcon;
  boolean tempUseDarkSky = useDarkSky;

  boolean tempUseThin = useThin;
  boolean tempUseThinAmbient = useThinAmbient;
  boolean tempUseGrayInfoAmbient = useGrayInfoAmbient;

  ArrayList<UpdatesRequired> updatesRequired = new ArrayList<>();

  Log.d(TAG, "timestamp: " + dataMap.getLong("timestamp"));

  showTemperature = dataMap.getBoolean("show_temperature", false);
  useCelsius = dataMap.getBoolean("use_celsius");
  showWeatherIcon = dataMap.getBoolean("show_weather", false);
  darkSkyAPIKey = dataMap.getString("dark_sky_api_key");

  showTemperatureFractional = dataMap.getBoolean("show_temperature_decimal");

  useThin = dataMap.getBoolean("use_thin");
  useThinAmbient = dataMap.getBoolean("use_thin_ambient");
  useGrayInfoAmbient = dataMap.getBoolean("use_gray_info_ambient");
  showInfoBarAmbient = dataMap.getBoolean("show_infobar_ambient");

  showBattery = dataMap.getBoolean("show_battery", true);
  showWearIcon = dataMap.getBoolean("show_wear_icon", false);

  useDarkSky = dataMap.getBoolean("use_dark_sky", false);

  advanced = dataMap.getBoolean("advanced", false);

  savePreferences();
  if (tempUseDarkSky != useDarkSky || showTemperature != tempShowTemperature || showWeatherIcon
      != tempShowWeatherIcon) {  //detect if weather related settings has changed
    updatesRequired.add(UpdatesRequired.WEATHER);
  }

  if (tempUseThin != useThin || tempUseThinAmbient != useThinAmbient || tempUseGrayInfoAmbient != useGrayInfoAmbient) { // check if font needs update

    updatesRequired.add(UpdatesRequired.FONT);
  }

  return updatesRequired;

}
 
Example 19
Source File: AttractionsActivity.java    From wear-os-samples with Apache License 2.0 4 votes vote down vote up
@Override
protected ArrayList<Attraction> doInBackground(Uri... params) {
    mAttractions.clear();

    // Connect to Play Services and the Wearable API
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(mContext)
            .addApi(Wearable.API)
            .build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(
            Constants.GOOGLE_API_CLIENT_TIMEOUT_S, TimeUnit.SECONDS);

    if (!connectionResult.isSuccess() || !googleApiClient.isConnected()) {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG,
                connectionResult.getErrorCode()));
        return null;
    }

    Uri attractionsUri = params[0];
    DataApi.DataItemResult dataItemResult =
            Wearable.DataApi.getDataItem(googleApiClient, attractionsUri).await();

    if (dataItemResult.getStatus().isSuccess() && dataItemResult.getDataItem() != null) {
        DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItemResult.getDataItem());
        List<DataMap> attractionsData =
                dataMapItem.getDataMap().getDataMapArrayList(Constants.EXTRA_ATTRACTIONS);

        // Loop through each attraction, adding them to the list
        Iterator<DataMap> itr = attractionsData.iterator();
        while (itr.hasNext()) {
            DataMap attractionData = itr.next();

            Attraction attraction = new Attraction();
            attraction.name = attractionData.getString(Constants.EXTRA_TITLE);
            attraction.description =
                    attractionData.getString(Constants.EXTRA_DESCRIPTION);
            attraction.city = attractionData.get(Constants.EXTRA_CITY);
            attraction.distance =
                    attractionData.getString(Constants.EXTRA_DISTANCE);
            attraction.location = new LatLng(
                    attractionData.getDouble(Constants.EXTRA_LOCATION_LAT),
                    attractionData.getDouble(Constants.EXTRA_LOCATION_LNG));
            attraction.image = Utils.loadBitmapFromAsset(googleApiClient,
                    attractionData.getAsset(Constants.EXTRA_IMAGE));
            attraction.secondaryImage = Utils.loadBitmapFromAsset(googleApiClient,
                    attractionData.getAsset(Constants.EXTRA_IMAGE_SECONDARY));

            mAttractions.add(attraction);
        }
    }

    googleApiClient.disconnect();

    return mAttractions;
}
 
Example 20
Source File: BIGChart.java    From NightWatch with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    DataMap dataMap = DataMap.fromBundle(intent.getBundleExtra("data"));
    if (layoutSet) {
        wakeLock.acquire(50);
        sgvLevel = dataMap.getLong("sgvLevel");
        batteryLevel = dataMap.getInt("batteryLevel");
        datetime = dataMap.getDouble("timestamp");
        rawString = dataMap.getString("rawString");
        sgvString = dataMap.getString("sgvString");
        batteryString = dataMap.getString("battery");
        mSgv.setText(dataMap.getString("sgvString"));

        if(ageLevel()<=0) {
            mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        } else {
            mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
        }

        final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(BIGChart.this);
        mTime.setText(timeFormat.format(System.currentTimeMillis()));

        showAgoRawBatt();

        String delta = dataMap.getString("delta");

        if (delta.endsWith(" mg/dl")) {
            mDelta.setText(delta.substring(0, delta.length() - 6));
        } else if (delta.endsWith(" mmol")) {
            mDelta.setText(delta.substring(0, delta.length() - 5));
        }

        if (chart != null) {
            addToWatchSet(dataMap);
            setupCharts();
        }
        mRelativeLayout.measure(specW, specH);
        mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(),
                mRelativeLayout.getMeasuredHeight());
        invalidate();
        setColor();

        //start animation?
        // dataMap.getDataMapArrayList("entries") == null -> not on "resend data".
        if (sharedPrefs.getBoolean("animation", false) && dataMap.getDataMapArrayList("entries") == null && (sgvString.equals("100") || sgvString.equals("5.5") || sgvString.equals("5,5"))) {
            startAnimation();
        }


    } else {
        Log.d("ERROR: ", "DATA IS NOT YET SET");
    }
}