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

The following examples show how to use com.google.android.gms.wearable.DataMap#getBoolean() . 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: MainActivity.java    From PixelWatchFace with GNU General Public License v3.0 6 votes vote down vote up
private void updateStatus(DataMap dataMap) {
  String TAG = "updateStatus";
  try {
    long timestamp = dataMap.getLong("wear_timestamp");
    boolean mShowTemperature = dataMap.getBoolean("show_temperature");
    boolean mUseCelsius = dataMap.getBoolean("use_celsius");
    boolean mShowWeather = dataMap.getBoolean("show_weather");

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(timestamp);


  } catch (Exception e) {
    Log.e(TAG, "error processing DataMap");
    Log.e(TAG, e.toString());
  }
}
 
Example 2
Source File: RawDisplayData.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
private void updateStatus(DataMap dataMap) {
    WearUtil.getWakeLock("readingPrefs", 50);
    sBasalRate = dataMap.getString("currentBasal");
    sUploaderBattery = dataMap.getString("battery");
    sRigBattery = dataMap.getString("rigBattery");
    detailedIOB = dataMap.getBoolean("detailedIob");
    sIOB1 = dataMap.getString("iobSum") + "U";
    sIOB2 = dataMap.getString("iobDetail");
    sCOB1 = "Carb";
    sCOB2 = dataMap.getString("cob");
    sBgi = dataMap.getString("bgi");
    showBGI = dataMap.getBoolean("showBgi");
    externalStatusString = dataMap.getString("externalStatusString");
    batteryLevel = dataMap.getInt("batteryLevel");
    openApsStatus = dataMap.getLong("openApsStatus");
}
 
Example 3
Source File: CollectionActivity.java    From arcgis-runtime-demos-android with Apache License 2.0 6 votes vote down vote up
/**
 * Handles a status response. The status response indicates whether the
 * feature was successfully collected or not, and if not, a reason why.
 *
 * @param item the DataItem received from the mobile device
 */
private void handleStatusResponse(DataItem item) {
  // Gets the TextView that will be used to display the status
  TextView text = (TextView) findViewById(R.id.text);
  DataMap dm = DataMapItem.fromDataItem(item).getDataMap();
  boolean success = dm.getBoolean("success");
  // If the event was successfully, show a success message in green
  if (success) {
    text.setText(R.string.collect_success);
    text.setTextColor(Color.GREEN);
  } else {
    // If it failed, show the failure reason in red
    String reason = dm.getString("reason");
    text.setText(String.format("%s\n%s", getString(R.string.collect_failure), reason));
    text.setTextColor(Color.RED);
  }
  // After 2 seconds, finish the activity
  new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
      CollectionActivity.this.finish();
    }
  }, 2000);
}
 
Example 4
Source File: WearService.java    From android-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
    super.onDataChanged(dataEventBuffer);

    //This method will call while any changes in data map occurs from watch side
    //This is data map. So, message delivery is guaranteed.
    for (DataEvent dataEvent : dataEventBuffer) {

        //Check for only those data who changed
        if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
            DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();

            //Check if the data map path matches with the step tracking status path
            String path = dataEvent.getDataItem().getUri().getPath();
            if (path.equals(STEP_TRACKING_STATUS_PATH)) {

                //Read the values
                boolean isTracking = dataMap.getBoolean("status");
                long timeStamp = dataMap.getLong("status-time");

                //send broadcast to update the UI in MainActivity based on the tracking status
                Intent intent = new Intent(TRACKING_STATUS_ACTION);
                intent.putExtra("status", isTracking);
                intent.putExtra("status-time", timeStamp);
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

                Log.d("Tracking status: ", isTracking + " Time: " + timeStamp);
            }
        }
    }
}
 
Example 5
Source File: ListenerService.java    From xDrip 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 6
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 7
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 8
Source File: WatchUpdaterService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
private void syncPrefData(DataMap dataMap) {
    boolean enable_wearG5 = dataMap.getBoolean("enable_wearG5", false);
    boolean force_wearG5 = dataMap.getBoolean("force_wearG5", false);
    String node_wearG5 = dataMap.getString("node_wearG5", "");
    String dex_txid = dataMap.getString("dex_txid", "");
    int bridge_battery = dataMap.getInt("bridge_battery", -1);//Used in DexCollectionService
    int nfc_sensor_age = dataMap.getInt("nfc_sensor_age", -1);//Used in DexCollectionService LimiTTer
    boolean bg_notifications_watch = dataMap.getBoolean("bg_notifications_watch", false);
    boolean persistent_high_alert_enabled_watch = dataMap.getBoolean("persistent_high_alert_enabled_watch", false);
    boolean show_wear_treatments = dataMap.getBoolean("show_wear_treatments", false);

    boolean change = false;

    SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
    Log.d(TAG, "syncPrefData enable_wearG5: " + enable_wearG5 + " force_wearG5: " + force_wearG5 + " node_wearG5:" + node_wearG5 + " dex_txid: " + dex_txid);

    if (bridge_battery != mPrefs.getInt("bridge_battery", -1)) {//Used by DexCollectionService
        prefs.putInt("bridge_battery", bridge_battery);
        prefs.apply();
        Log.d(TAG, "syncPrefData commit bridge_battery: " + bridge_battery);
        CheckBridgeBattery.checkBridgeBattery();
        if (force_wearG5 && CheckBridgeBattery.checkForceWearBridgeBattery()) {
            force_wearG5 = false;
            change = true;
            Log.d(TAG, "syncPrefData disable_wearG5_on_lowbattery=true; switch force_wearG5:" + force_wearG5);
            String msg = getResources().getString(R.string.notify_when_wear_low_battery);
            JoH.static_toast_long(msg);
            sendWearLocalToast(msg, Toast.LENGTH_LONG);
        }
    }

    if (!node_wearG5.equals(mPrefs.getString("node_wearG5", ""))) {
        change = true;
        prefs.putString("node_wearG5", node_wearG5);
        Log.d(TAG, "syncPrefData node_wearG5:" + node_wearG5);
    }

    if (/*force_wearG5 &&*/ force_wearG5 != mPrefs.getBoolean("force_wearG5", false)) {
        change = true;
        prefs.putBoolean("force_wearG5", force_wearG5);
        Log.d(TAG, "syncPrefData commit force_wearG5:" + force_wearG5);
        if (force_wearG5) {
            final PendingIntent pendingIntent = android.app.PendingIntent.getActivity(xdrip.getAppContext(), 0, new Intent(xdrip.getAppContext(), Home.class), android.app.PendingIntent.FLAG_UPDATE_CURRENT);
            showNotification("Force Wear Enabled", node_wearG5 + " Watch has enabled Force Wear Collection Service", pendingIntent, 771, true, true, true);
        }
    }

    if (nfc_sensor_age != mPrefs.getInt("nfc_sensor_age", 0)) {//Used by DexCollectionService
        change = true;
        prefs.putInt("nfc_sensor_age", nfc_sensor_age);
        Log.d(TAG, "syncPrefData commit nfc_sensor_age: " + nfc_sensor_age);
    }

    if (bg_notifications_watch != mPrefs.getBoolean("bg_notifications_watch", false)) {
        change = true;
        prefs.putBoolean("bg_notifications_watch", bg_notifications_watch);
        Log.d(TAG, "syncPrefData commit bg_notifications_watch: " + bg_notifications_watch);
    }
    PersistentStore.setBoolean("bg_notifications_watch", bg_notifications_watch);
    PersistentStore.setBoolean("persistent_high_alert_enabled_watch", persistent_high_alert_enabled_watch);

    if (/*enable_wearG5 &&*/ enable_wearG5 != mPrefs.getBoolean("enable_wearG5", false)) {
        change = true;
        prefs.putBoolean("enable_wearG5", enable_wearG5);
        Log.d(TAG, "syncPrefData commit enable_wearG5: " + enable_wearG5);
    }

    if (show_wear_treatments != mPrefs.getBoolean("show_wear_treatments", false)) {
        change = true;
        prefs.putBoolean("show_wear_treatments", show_wear_treatments);
        Log.d(TAG, "syncPrefData show_wear_treatments:" + show_wear_treatments);
    }

    if (change) {
        prefs.apply();
    } else if (!dex_txid.equals(mPrefs.getString("dex_txid", "default"))) {
        sendPrefSettings();
        processConnect();
    }
}
 
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: WatchUpdaterService.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
private void syncPrefData(DataMap dataMap) {
    boolean enable_wearG5 = dataMap.getBoolean("enable_wearG5", false);
    boolean force_wearG5 = dataMap.getBoolean("force_wearG5", false);
    String node_wearG5 = dataMap.getString("node_wearG5", "");
    String dex_txid = dataMap.getString("dex_txid", "");
    int bridge_battery = dataMap.getInt("bridge_battery", -1);//Used in DexCollectionService
    int nfc_sensor_age = dataMap.getInt("nfc_sensor_age", -1);//Used in DexCollectionService LimiTTer
    boolean bg_notifications_watch = dataMap.getBoolean("bg_notifications_watch", false);
    boolean persistent_high_alert_enabled_watch = dataMap.getBoolean("persistent_high_alert_enabled_watch", false);
    boolean show_wear_treatments = dataMap.getBoolean("show_wear_treatments", false);

    boolean change = false;

    SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(this).edit();
    Log.d(TAG, "syncPrefData enable_wearG5: " + enable_wearG5 + " force_wearG5: " + force_wearG5 + " node_wearG5:" + node_wearG5 + " dex_txid: " + dex_txid);

    if (bridge_battery != mPrefs.getInt("bridge_battery", -1)) {//Used by DexCollectionService
        prefs.putInt("bridge_battery", bridge_battery);
        prefs.apply();
        Log.d(TAG, "syncPrefData commit bridge_battery: " + bridge_battery);
        CheckBridgeBattery.checkBridgeBattery();
        if (force_wearG5 && CheckBridgeBattery.checkForceWearBridgeBattery()) {
            force_wearG5 = false;
            change = true;
            Log.d(TAG, "syncPrefData disable_wearG5_on_lowbattery=true; switch force_wearG5:" + force_wearG5);
            String msg = getResources().getString(R.string.notify_when_wear_low_battery);
            JoH.static_toast_long(msg);
            sendWearLocalToast(msg, Toast.LENGTH_LONG);
        }
    }

    if (!node_wearG5.equals(mPrefs.getString("node_wearG5", ""))) {
        change = true;
        prefs.putString("node_wearG5", node_wearG5);
        Log.d(TAG, "syncPrefData node_wearG5:" + node_wearG5);
    }

    if (/*force_wearG5 &&*/ force_wearG5 != mPrefs.getBoolean("force_wearG5", false)) {
        change = true;
        prefs.putBoolean("force_wearG5", force_wearG5);
        Log.d(TAG, "syncPrefData commit force_wearG5:" + force_wearG5);
        if (force_wearG5) {
            final PendingIntent pendingIntent = android.app.PendingIntent.getActivity(xdrip.getAppContext(), 0, new Intent(xdrip.getAppContext(), Home.class), android.app.PendingIntent.FLAG_UPDATE_CURRENT);
            showNotification("Force Wear Enabled", node_wearG5 + " Watch has enabled Force Wear Collection Service", pendingIntent, 771, true, true, true);
        }
    }

    if (nfc_sensor_age != mPrefs.getInt("nfc_sensor_age", 0)) {//Used by DexCollectionService
        change = true;
        prefs.putInt("nfc_sensor_age", nfc_sensor_age);
        Log.d(TAG, "syncPrefData commit nfc_sensor_age: " + nfc_sensor_age);
    }

    if (bg_notifications_watch != mPrefs.getBoolean("bg_notifications_watch", false)) {
        change = true;
        prefs.putBoolean("bg_notifications_watch", bg_notifications_watch);
        Log.d(TAG, "syncPrefData commit bg_notifications_watch: " + bg_notifications_watch);
    }
    PersistentStore.setBoolean("bg_notifications_watch", bg_notifications_watch);
    PersistentStore.setBoolean("persistent_high_alert_enabled_watch", persistent_high_alert_enabled_watch);

    if (/*enable_wearG5 &&*/ enable_wearG5 != mPrefs.getBoolean("enable_wearG5", false)) {
        change = true;
        prefs.putBoolean("enable_wearG5", enable_wearG5);
        Log.d(TAG, "syncPrefData commit enable_wearG5: " + enable_wearG5);
    }

    if (show_wear_treatments != mPrefs.getBoolean("show_wear_treatments", false)) {
        change = true;
        prefs.putBoolean("show_wear_treatments", show_wear_treatments);
        Log.d(TAG, "syncPrefData show_wear_treatments:" + show_wear_treatments);
    }

    if (change) {
        prefs.apply();
    } else if (!dex_txid.equals(mPrefs.getString("dex_txid", "default"))) {
        sendPrefSettings();
        processConnect();
    }
}
 
Example 11
Source File: WatchUpdaterService.java    From xDrip-plus 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 12
Source File: DataBundleUtil.java    From android_external_GmsLib with Apache License 2.0 4 votes vote down vote up
@Override
Boolean load(DataMap dataMap, String key) {
    return dataMap.getBoolean(key);
}
 
Example 13
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 14
Source File: QuizListenerService.java    From AndroidWearable-Samples with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    dataEvents.close();

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

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

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

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

                boolean correct = (i == correctAnswerIndex);
                Intent updateOperation = new Intent(this, UpdateQuestionService.class);
                // Give each intent a unique action.
                updateOperation.setAction("question_" + questionIndex + "_answer_" + i);
                updateOperation.setData(dataItem.getUri());
                updateOperation.putExtra(UpdateQuestionService.EXTRA_QUESTION_INDEX,
                        questionIndex);
                updateOperation.putExtra(UpdateQuestionService.EXTRA_QUESTION_CORRECT, correct);
                PendingIntent updateIntent = PendingIntent.getService(this, 0, updateOperation,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                Notification.Action action = new Notification.Action.Builder(
                        questionNumToDrawableId.get(i), null, updateIntent)
                        .build();
                wearableOptions.addAction(action).addPage(answerPage);
            }
            builder.extend(wearableOptions);
            Notification notification = builder.build();
            ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                    .notify(questionIndex, notification);
        } else if (event.getType() == DataEvent.TYPE_DELETED) {
            Uri uri = event.getDataItem().getUri();
            // URI's are of the form "/question/0", "/question/1" etc.
            // We use the question index as the notification id.
            int notificationId = Integer.parseInt(uri.getLastPathSegment());
            ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                    .cancel(notificationId);
        }
        // Delete the quiz report, if it exists.
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                .cancel(QUIZ_REPORT_NOTIF_ID);
    }
    googleApiClient.disconnect();
}
 
Example 15
Source File: HomeListenerService.java    From AndroidWearable-Samples with Apache License 2.0 4 votes vote down vote up
/**
 * Posts a local notification to show calendar card.
 */
private void UpdateNotificationForDataItem(DataItem dataItem) {
    DataMapItem mapDataItem = DataMapItem.fromDataItem(dataItem);
    DataMap data = mapDataItem.getDataMap();

    String description = data.getString(DESCRIPTION);
    if (TextUtils.isEmpty(description)) {
        description = "";
    } else {
        // Add a space between the description and the time of the event.
        description += " ";
    }
    String contentText;
    if (data.getBoolean(ALL_DAY)) {
        contentText = getString(R.string.desc_all_day, description);
    } else {
        String startTime = DateFormat.getTimeFormat(this).format(new Date(data.getLong(BEGIN)));
        String endTime = DateFormat.getTimeFormat(this).format(new Date(data.getLong(END)));
        contentText = getString(R.string.desc_time_period, description, startTime, endTime);
    }

    Intent deleteOperation = new Intent(this, DeleteService.class);
    // Use a unique identifier for the delete action.
    String deleteAction = "action_delete" + dataItem.getUri().toString() + sNotificationId;
    deleteOperation.setAction(deleteAction);
    deleteOperation.setData(dataItem.getUri());
    PendingIntent deleteIntent = PendingIntent.getService(this, 0, deleteOperation,
            PendingIntent.FLAG_ONE_SHOT);
    PendingIntent silentDeleteIntent = PendingIntent.getService(this, 1,
            deleteOperation.putExtra(EXTRA_SILENT, true), PendingIntent.FLAG_ONE_SHOT);

    Notification.Builder notificationBuilder = new Notification.Builder(this)
            .setContentTitle(data.getString(TITLE))
            .setContentText(contentText)
            .setSmallIcon(R.drawable.ic_launcher)
            .addAction(R.drawable.ic_menu_delete, getText(R.string.delete), deleteIntent)
            .setDeleteIntent(silentDeleteIntent)  // Delete DataItem if notification dismissed.
            .setLocalOnly(true)
            .setPriority(Notification.PRIORITY_MIN);

    // Set the event owner's profile picture as the notification background.
    Asset asset = data.getAsset(PROFILE_PIC);
    if (null != asset) {
        if (mGoogleApiClient.isConnected()) {
            DataApi.GetFdForAssetResult assetFdResult =
                    Wearable.DataApi.getFdForAsset(mGoogleApiClient, asset).await();
            if (assetFdResult.getStatus().isSuccess()) {
                Bitmap profilePic = BitmapFactory.decodeStream(assetFdResult.getInputStream());
                notificationBuilder.extend(new Notification.WearableExtender()
                        .setBackground(profilePic));
            } else if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "asset fetch failed with statusCode: "
                        + assetFdResult.getStatus().getStatusCode());
            }
        } else {
            Log.e(TAG, "Failed to set notification background"
                     + " - Client disconnected from Google Play Services");
        }
    }
    Notification card = notificationBuilder.build();

    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
            .notify(sNotificationId, card);

    sNotificationIdByDataItemUri.put(dataItem.getUri(), sNotificationId++);
}