@Override
  public void onDestroy() {
    disconnectExit();
    super.onDestroy();
    serviceThread.quit();

    if (Preferences.logging) Log.d(MetaWatch.TAG, "MetaWatchService.onDestroy()");
    PreferenceManager.getDefaultSharedPreferences(context)
        .unregisterOnSharedPreferenceChangeListener(prefChangeListener);

    Monitors.stop(this);
    removeNotification();
    notifyClients();
    mClients.clear();
  }
 void broadcastConnection(boolean connected) {
   if (connected != lastConnectionState) {
     lastConnectionState = connected;
     Intent intent = new Intent("org.metawatch.manager.CONNECTION_CHANGE");
     intent.putExtra("state", connected);
     sendBroadcast(intent);
     notifyClients();
     if (Preferences.logging)
       Log.d(
           MetaWatch.TAG,
           "MetaWatchService.broadcastConnection(): Broadcast connection change: state='"
               + connected
               + "'");
     Protocol.resetLCDDiffBuffer();
   }
 }
  public void updateNotification() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean hideNotificationIcon = sharedPreferences.getBoolean("HideNotificationIcon", false);
    if (Preferences.logging)
      Log.d(
          MetaWatch.TAG,
          "MetaWatchService.updateNotification(): hideNotificationIcon=" + hideNotificationIcon);
    switch (connectionState) {
      case ConnectionState.CONNECTING:
        notification.icon =
            (hideNotificationIcon ? R.drawable.transparent_square : R.drawable.disconnected);
        notification.setLatestEventInfo(
            this, "MetaWatch Manager", "Connecting", createNotificationPendingIntent());
        broadcastConnection(false);
        break;
      case ConnectionState.CONNECTED:
        notification.icon =
            (hideNotificationIcon ? R.drawable.transparent_square : R.drawable.connected);
        notification.setLatestEventInfo(
            this,
            getResources().getString(R.string.app_name),
            getResources().getString(R.string.connection_connected),
            createNotificationPendingIntent());
        broadcastConnection(true);
        break;
      default:
        notification.icon =
            (hideNotificationIcon ? R.drawable.transparent_square : R.drawable.disconnected);
        notification.setLatestEventInfo(
            this,
            getResources().getString(R.string.app_name),
            getResources().getString(R.string.connection_disconnected),
            createNotificationPendingIntent());
        broadcastConnection(false);
        break;
    }

    startForeground(1, notification);
    notifyClients();
  }
  public synchronized WeatherData update(Context context, WeatherData weatherData) {
    try {
      if (isUpdateRequired(weatherData)) {
        if (Preferences.logging) Log.d(MetaWatch.TAG, "Monitors.updateWeatherDataGoogle(): start");

        String queryString;
        if (isGeolocationDataUsed()) {
          GoogleGeoCoderLocationData locationData =
              reverseLookupGeoLocation(context, LocationData.latitude, LocationData.longitude);
          weatherData.locationName = locationData.getLocationName();
          long lat = (long) (LocationData.latitude * 1000000);
          long lon = (long) (LocationData.longitude * 1000000);
          queryString = "http://www.google.com/ig/api?weather=,,," + lat + "," + lon;
        } else {
          String weatherLocation =
              Preferences.weatherCity.replace(",", " ").replace("  ", " ").replace(" ", "%20");
          queryString = "http://www.google.com/ig/api?weather=" + weatherLocation;
          weatherData.locationName = Preferences.weatherCity;
        }

        HttpClient hc = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(queryString);
        HttpResponse rp = hc.execute(httpGet);

        if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
          String s = EntityUtils.toString(rp.getEntity());
          if (Preferences.logging) Log.d(MetaWatch.TAG, "Got weather data " + s);

          SAXParserFactory spf = SAXParserFactory.newInstance();
          SAXParser sp = spf.newSAXParser();
          XMLReader xr = sp.getXMLReader();

          GoogleWeatherHandler gwh = new GoogleWeatherHandler();
          xr.setContentHandler(gwh);
          xr.parse(new InputSource(new StringReader(s)));
          WeatherSet ws = gwh.getWeatherSet();
          if (ws == null || ws.getWeatherCurrentCondition() == null) {
            if (Preferences.logging)
              Log.e(MetaWatch.TAG, "Google Weather API did not respond with valid data: " + s);
          } else {
            WeatherCurrentCondition wcc = ws.getWeatherCurrentCondition();

            ArrayList<WeatherForecastCondition> conditions = ws.getWeatherForecastConditions();

            int days = conditions.size();
            weatherData.forecast = new Forecast[days];

            for (int i = 0; i < days; ++i) {
              WeatherForecastCondition wfc = conditions.get(i);

              weatherData.forecast[i] = new Forecast();
              weatherData.forecast[i].setDay(wfc.getDayofWeek());
              weatherData.forecast[i].setIcon(getIcon(wfc.getCondition().toLowerCase()));

              if (Preferences.weatherCelsius) {
                weatherData.forecast[i].setTempHigh(wfc.getTempMaxCelsius());
                weatherData.forecast[i].setTempLow(wfc.getTempMinCelsius());
              } else {
                weatherData.forecast[i].setTempHigh(
                    WeatherUtils.celsiusToFahrenheit(wfc.getTempMaxCelsius()));
                weatherData.forecast[i].setTempLow(
                    WeatherUtils.celsiusToFahrenheit(wfc.getTempMinCelsius()));
              }

              if (Preferences.logging)
                Log.d(MetaWatch.TAG, "Forecast #" + i + ": " + weatherData.forecast[i]);
            }

            weatherData.celsius = Preferences.weatherCelsius;

            String cond = wcc.getCondition();
            weatherData.condition = cond;

            if (Preferences.weatherCelsius) {
              weatherData.temp = Integer.toString(wcc.getTempCelcius());
            } else {
              weatherData.temp = Integer.toString(wcc.getTempFahrenheit());
            }

            cond = cond.toLowerCase();

            weatherData.icon = getIcon(cond);
            weatherData.received = true;
            weatherData.timeStamp = System.currentTimeMillis();

            Idle.updateIdle(context, true);
            MetaWatchService.notifyClients();
          }
        }
      }

    } catch (Exception e) {
      if (Preferences.logging) Log.e(MetaWatch.TAG, "Exception while retreiving weather", e);
    } finally {
      if (Preferences.logging) Log.d(MetaWatch.TAG, "Monitors.updateWeatherData(): finish");
    }

    return weatherData;
  }