Example usage for android.text.format Time setToNow

List of usage examples for android.text.format Time setToNow

Introduction

In this page you can find the example usage for android.text.format Time setToNow.

Prototype

public void setToNow() 

Source Link

Document

Sets the time of the given Time object to the current time.

Usage

From source file:com.android.datetimepicker.date.MonthView.java

/**
 * Sets all the parameters for displaying this week. The only required
 * parameter is the week number. Other parameters have a default value and
 * will only update if a new value is included, except for focus month,
 * which will always default to no focus month if no value is passed in. See
 * {@link #VIEW_PARAMS_HEIGHT} for more info on parameters.
 *
 * @param params A map of the new parameters, see
 *            {@link #VIEW_PARAMS_HEIGHT}
 *//*from   ww w  .j a v  a  2 s .c  om*/
public void setMonthParams(HashMap<String, Integer> params) {
    if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) {
        throw new InvalidParameterException("You must specify month and year for this view");
    }
    setTag(params);
    // We keep the current value for any params not present
    if (params.containsKey(VIEW_PARAMS_HEIGHT)) {
        mRowHeight = params.get(VIEW_PARAMS_HEIGHT);
        if (mRowHeight < MIN_HEIGHT) {
            mRowHeight = MIN_HEIGHT;
        }
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_DAY)) {
        mSelectedDay = params.get(VIEW_PARAMS_SELECTED_DAY);
    }

    // Allocate space for caching the day numbers and focus values
    mMonth = params.get(VIEW_PARAMS_MONTH);
    mYear = params.get(VIEW_PARAMS_YEAR);

    // Figure out what day today is
    final Time today = new Time(Time.getCurrentTimezone());
    today.setToNow();
    mHasToday = false;
    mToday = -1;

    mCalendar.set(Calendar.MONTH, mMonth);
    mCalendar.set(Calendar.YEAR, mYear);
    mCalendar.set(Calendar.DAY_OF_MONTH, 1);
    mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK);

    if (params.containsKey(VIEW_PARAMS_WEEK_START)) {
        mWeekStart = params.get(VIEW_PARAMS_WEEK_START);
    } else {
        mWeekStart = mCalendar.getFirstDayOfWeek();
    }

    mNumCells = Utils.getDaysInMonth(mMonth, mYear);
    for (int i = 0; i < mNumCells; i++) {
        final int day = i + 1;
        if (sameDay(day, today)) {
            mHasToday = true;
            mToday = day;
        }
    }
    mNumRows = calculateNumRows();

    // Invalidate cached accessibility information.
    mTouchHelper.invalidateRoot();
}

From source file:com.nadmm.airports.DownloadActivity.java

protected void cleanupExpiredData() {
    SQLiteDatabase catalogDb = mDbManager.getCatalogDb();

    Time now = new Time();
    now.setToNow();
    String today = now.format3339(true);

    Cursor c = mDbManager.getAllFromCatalog();
    if (c.moveToFirst()) {
        do {// www .j  a  va 2  s .  co m
            // Check and delete all the expired databases
            String end = c.getString(c.getColumnIndex(Catalog.END_DATE));
            if (end.compareTo(today) < 0) {
                // This database has expired, remove it
                Integer _id = c.getInt(c.getColumnIndex(Catalog._ID));
                String dbName = c.getString(c.getColumnIndex(Catalog.DB_NAME));
                File file = new File(DatabaseManager.DATABASE_DIR, dbName);
                if (catalogDb.isOpen() && file.delete()) {
                    // Now delete the catalog entry for the file
                    catalogDb.delete(Catalog.TABLE_NAME, Catalog._ID + "=?",
                            new String[] { Integer.toString(_id) });
                }
            }
        } while (c.moveToNext());
    }
    c.close();
}

From source file:com.example.rafa.sunshine.app.experiments.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.//  w  w w . j  a  v  a 2 s. co m
 */

//Agafa les dades en format JSON i les introdueix a la db.
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + inserted + " Inserted");

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:com.appsimobile.appsii.module.appsiagenda.MonthView.java

/**
 * Sets all the parameters for displaying this week. The only required
 * parameter is the week number. Other parameters have a default value and
 * will only update if a new value is included, except for focus month,
 * which will always default to no focus month if no value is passed in. See
 * {@link #VIEW_PARAMS_HEIGHT} for more info on parameters.
 *
 * @param params A map of the new parameters, see
 * {@link #VIEW_PARAMS_HEIGHT}//from   www.j av a  2  s. c  o  m
 */
public void setMonthParams(SimpleArrayMap<String, Integer> params) {
    if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) {
        throw new InvalidParameterException("You must specify month and year for this view");
    }
    setTag(params);
    // We keep the current value for any params not present
    if (params.containsKey(VIEW_PARAMS_HEIGHT)) {
        mRowHeight = params.get(VIEW_PARAMS_HEIGHT);
        if (mRowHeight < MIN_HEIGHT) {
            mRowHeight = MIN_HEIGHT;
        }
    }
    if (params.containsKey(VIEW_PARAMS_SELECTED_DAY)) {
        mSelectedDay = params.get(VIEW_PARAMS_SELECTED_DAY);
    }

    mStartJulianDay = params.get(VIEW_PARAMS_START_JULIAN_DAY);

    // Allocate space for caching the day numbers and focus values
    mMonth = params.get(VIEW_PARAMS_MONTH);
    mYear = params.get(VIEW_PARAMS_YEAR);

    // Figure out what day today is
    final Time today = new Time(Time.getCurrentTimezone());
    today.setToNow();
    mHasToday = false;
    mToday = -1;

    mCalendar.set(Calendar.MONTH, mMonth);
    mCalendar.set(Calendar.YEAR, mYear);
    mCalendar.set(Calendar.DAY_OF_MONTH, 1);
    mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK);

    if (params.containsKey(VIEW_PARAMS_WEEK_START)) {
        mWeekStart = params.get(VIEW_PARAMS_WEEK_START);
    } else {
        mWeekStart = mCalendar.getFirstDayOfWeek();
    }

    mNumCells = Utils.getDaysInMonth(mMonth, mYear);
    for (int i = 0; i < mNumCells; i++) {
        final int day = i + 1;
        if (sameDay(day, today)) {
            mHasToday = true;
            mToday = day;
        }
    }
    mNumRows = calculateNumRows();

    // Invalidate cached accessibility information.
    mTouchHelper.invalidateRoot();
}

From source file:uk.org.openseizuredetector.SdServer.java

/**
 * Sends SMS Alarms to the telephone numbers specified in mSMSNumbers[]
 */// www  . j  a  v a2 s. c om
public void sendSMSAlarm() {
    if (mSMSAlarm) {
        Log.v(TAG, "sendSMSAlarm() - Sending to " + mSMSNumbers.length + " Numbers");
        Time tnow = new Time(Time.getCurrentTimezone());
        tnow.setToNow();
        String dateStr = tnow.format("%Y-%m-%d %H-%M-%S");
        SmsManager sm = SmsManager.getDefault();
        for (int i = 0; i < mSMSNumbers.length; i++) {
            Log.v(TAG, "sendSMSAlarm() - Sending to " + mSMSNumbers[i]);
            sm.sendTextMessage(mSMSNumbers[i], null, mSMSMsgStr + " - " + dateStr, null, null);
        }
    } else {
        Log.v(TAG, "sendSMSAlarm() - SMS Alarms Disabled - not doing anything!");
        Toast toast = Toast.makeText(getApplicationContext(), "SMS Alarms Disabled - not doing anything!",
                Toast.LENGTH_SHORT);
        toast.show();
    }
}

From source file:uk.org.openseizuredetector.SdServer.java

/**
 * Write data to SD card - writes to data log file unless alarm=true,
 * in which case writes to alarm log file.
 */// w ww  .  jav a 2  s  . c  o m
public void writeToSD(boolean alarm) {
    Log.v(TAG, "writeToSD(" + alarm + ")");
    Time tnow = new Time(Time.getCurrentTimezone());
    tnow.setToNow();
    String dateStr = tnow.format("%Y-%m-%d");

    // Select filename depending on 'alarm' parameter.
    String fname;
    if (alarm)
        fname = "AlarmLog";
    else
        fname = "DataLog";

    fname = fname + "_" + dateStr + ".txt";
    // Open output directory on SD Card.
    if (isExternalStorageWritable()) {
        try {
            FileWriter of = new FileWriter(getDataStorageDir().toString() + "/" + fname, true);
            if (sdData != null) {
                Log.v(TAG, "writing sdData.toString()");
                of.append(sdData.toString() + "\n");
            }
            of.close();
        } catch (Exception ex) {
            Log.e(TAG, "writeAlarmToSD - error " + ex.toString());
        }
    } else {
        Log.e(TAG, "ERROR - Can not Write to External Folder");
    }
}

From source file:uk.org.openseizuredetector.SdServer.java

/** 
 * Checks the status of the connection to the pebble watch,
 * and sets class variables for use by other functions.
 * If the watch app is not running, it attempts to re-start it.
 *///from ww  w.  j  a v a2 s  .c  o  m
public void getPebbleStatus() {
    Time tnow = new Time(Time.getCurrentTimezone());
    tnow.setToNow();
    // Check we are actually connected to the pebble.
    sdData.pebbleConnected = PebbleKit.isWatchConnected(this);
    // And is the pebble_sd app running?
    // set mPebbleAppRunningCheck has been false for more than 10 seconds
    // the app is not talking to us
    // mPebbleAppRunningCheck is set to true in the receiveData handler. 
    if (!mPebbleAppRunningCheck && ((tnow.toMillis(false) - mPebbleStatusTime.toMillis(false)) > 10000)) {
        Log.v(TAG, "tdiff = " + (tnow.toMillis(false) - mPebbleStatusTime.toMillis(false)));
        sdData.pebbleAppRunning = false;
        Log.v(TAG, "Pebble App Not Running - Attempting to Re-Start");
        startWatchApp();
        getPebbleSdSettings();
        if (mAudibleFaultWarning) {
            faultWarningBeep();
        }
    } else {
        sdData.pebbleAppRunning = true;
    }

    // if we have confirmation that the app is running, reset the
    // status time to now and initiate another check.
    if (mPebbleAppRunningCheck) {
        mPebbleAppRunningCheck = false;
        mPebbleStatusTime.setToNow();
    }

    if (!sdData.haveSettings) {
        Log.v(TAG, "getPebbleStatus() - no settings received yet - requesting");
        getPebbleSdSettings();
    }
}

From source file:uk.org.openseizuredetector.SdServer.java

/**
 * Set this server to receive pebble data by registering it as
 * A PebbleDataReceiver/*from w  ww .j  a  va 2 s  .co m*/
 */
private void startPebbleServer() {
    Log.v(TAG, "StartPebbleServer()");
    final Handler handler = new Handler();
    msgDataHandler = new PebbleKit.PebbleDataReceiver(SD_UUID) {
        @Override
        public void receiveData(final Context context, final int transactionId, final PebbleDictionary data) {
            Log.v(TAG,
                    "Received message from Pebble - data type=" + data.getUnsignedIntegerAsLong(KEY_DATA_TYPE));
            // If we have a message, the app must be running
            mPebbleAppRunningCheck = true;
            PebbleKit.sendAckToPebble(context, transactionId);
            //Log.v(TAG,"Message is: "+data.toJsonString());
            if (data.getUnsignedIntegerAsLong(KEY_DATA_TYPE) == DATA_TYPE_RESULTS) {
                Log.v(TAG, "DATA_TYPE = Results");
                sdData.dataTime.setToNow();
                Log.v(TAG, "sdData.dataTime=" + sdData.dataTime);

                sdData.alarmState = data.getUnsignedIntegerAsLong(KEY_ALARMSTATE);
                sdData.maxVal = data.getUnsignedIntegerAsLong(KEY_MAXVAL);
                sdData.maxFreq = data.getUnsignedIntegerAsLong(KEY_MAXFREQ);
                sdData.specPower = data.getUnsignedIntegerAsLong(KEY_SPECPOWER);
                sdData.roiPower = data.getUnsignedIntegerAsLong(KEY_ROIPOWER);
                sdData.alarmPhrase = "Unknown";
                if (sdData.alarmState == 0) {
                    sdData.alarmPhrase = "OK";
                }
                if (sdData.alarmState == 1) {
                    sdData.alarmPhrase = "WARNING";
                    if (mLogAlarms) {
                        Log.v(TAG, "WARNING - Loggin to SD Card");
                        writeAlarmToSD();
                        logData();
                    } else {
                        Log.v(TAG, "WARNING");
                    }
                    warningBeep();
                }
                if (sdData.alarmState == 2) {
                    sdData.alarmPhrase = "ALARM";
                    if (mLogAlarms) {
                        Log.v(TAG, "***ALARM*** - Loggin to SD Card");
                        writeAlarmToSD();
                        logData();
                    } else {
                        Log.v(TAG, "***ALARM***");
                    }
                    // Make alarm beep tone
                    alarmBeep();
                    // Send SMS Alarm.
                    if (mSMSAlarm) {
                        Time tnow = new Time(Time.getCurrentTimezone());
                        tnow.setToNow();
                        // limit SMS alarms to one per minute
                        if ((tnow.toMillis(false) - mSMSTime.toMillis(false)) > 60000) {
                            sendSMSAlarm();
                            mSMSTime = tnow;
                        }
                    }
                }

                // Read the data that has been sent, and convert it into
                // an integer array.
                byte[] byteArr = data.getBytes(KEY_SPEC_DATA);
                IntBuffer intBuf = ByteBuffer.wrap(byteArr).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
                int[] intArray = new int[intBuf.remaining()];
                intBuf.get(intArray);
                for (int i = 0; i < intArray.length; i++) {
                    sdData.simpleSpec[i] = intArray[i];
                }

            }
            if (data.getUnsignedIntegerAsLong(KEY_DATA_TYPE) == DATA_TYPE_SETTINGS) {
                Log.v(TAG, "DATA_TYPE = Settings");
                sdData.alarmFreqMin = data.getUnsignedIntegerAsLong(KEY_ALARM_FREQ_MIN);
                sdData.alarmFreqMax = data.getUnsignedIntegerAsLong(KEY_ALARM_FREQ_MAX);
                sdData.nMin = data.getUnsignedIntegerAsLong(KEY_NMIN);
                sdData.nMax = data.getUnsignedIntegerAsLong(KEY_NMAX);
                sdData.warnTime = data.getUnsignedIntegerAsLong(KEY_WARN_TIME);
                sdData.alarmTime = data.getUnsignedIntegerAsLong(KEY_ALARM_TIME);
                sdData.alarmThresh = data.getUnsignedIntegerAsLong(KEY_ALARM_THRESH);
                sdData.alarmRatioThresh = data.getUnsignedIntegerAsLong(KEY_ALARM_RATIO_THRESH);
                sdData.batteryPc = data.getUnsignedIntegerAsLong(KEY_BATTERY_PC);
                sdData.haveSettings = true;
            }
        }
    };
    PebbleKit.registerReceivedDataHandler(this, msgDataHandler);
}

From source file:org.smap.smapTask.android.activities.MainMapsActivity.java

private void formChooser(Intent intent, String instancePath) {
    String formPath = intent.getStringExtra(FormEntryActivity.KEY_FORMPATH);
    Intent i = null;/*from w w  w  . j ava  2  s. c  o m*/

    // Create the local task and get the task id as a string to pass to the form entry activity
    Time t = new Time();
    t.setToNow();
    long tid = -1;
    try {
        TaskAssignment ta = new TaskAssignment();
        /*
         * TODO Implement
        task.scheduledStart = t.toMillis(false);
        task.status = "open";
        task.taskForm = STFileUtils.getFileName(formPath);
        tid = mTda.createTask(-1, "local", null, task);
        */
    } catch (Exception e) {
        e.printStackTrace(); // TODO handle exception
    }

    i = new Intent("org.smap.smapTask.android.action.FormEntry");
    i.putExtra(FormEntryActivity.KEY_FORMPATH, formPath);
    i.putExtra(FormEntryActivity.KEY_TASK, tid);
    if (instancePath != null) {
        i.putExtra(FormEntryActivity.KEY_INSTANCEPATH, instancePath);
    }
    startActivity(i);
}