Example usage for android.text.format Time Time

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

Introduction

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

Prototype

public Time() 

Source Link

Document

Construct a Time object in the default timezone.

Usage

From source file:com.nextgis.firereporter.GetFiresService.java

protected void Prepare() {
    mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mnCurrentExec = 0;// ww  w.  j ava  2  s .  c  o  m
    mmoFires = new HashMap<Long, FireItem>();

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nUserCount = 0;
    nNasaCount = 0;
    nScanexCount = 0;
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
    //stackBuilder.addNextIntent(new Intent(this, ScanexNotificationsActivity.class));
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_fire_small)
            .setContentTitle(getString(R.string.stNewFireNotifications));
    mBuilder.setContentIntent(resultPendingIntent);

    Intent delIntent = new Intent(this, GetFiresService.class);
    delIntent.putExtra(COMMAND, SERVICE_NOTIFY_DISMISSED);
    PendingIntent deletePendingIntent = PendingIntent.getService(this, 0, delIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setDeleteIntent(deletePendingIntent);

    mInboxStyle = new NotificationCompat.InboxStyle();
    mInboxStyle.setBigContentTitle(getString(R.string.stNewFireNotificationDetailes));

    LoadScanexData();

    mSanextCookieTime = new Time();
    mSanextCookieTime.setToNow();
    msScanexLoginCookie = new String("not_set");

    mFillDataHandler = new Handler() {
        public void handleMessage(Message msg) {

            mnCurrentExec--;

            Bundle resultData = msg.getData();
            boolean bHaveErr = resultData.getBoolean(ERROR);
            if (bHaveErr) {
                SendError(resultData.getString(ERR_MSG));
            } else {
                int nType = resultData.getInt(SOURCE);
                String sData = resultData.getString(JSON);
                switch (nType) {
                case 3:
                    FillScanexData(nType, sData);
                    break;
                case 4:
                    msScanexLoginCookie = sData;
                    mSanextCookieTime.setToNow();
                    GetScanexData(false);
                    break;
                default:
                    FillData(nType, sData);
                    break;
                }
            }
            GetDataStoped();
        };
    };
}

From source file:com.nextgis.mobile.services.TrackerService.java

protected void ScheduleNextUpdate(Context context, String action, long nMinTimeBetweenSend,
        boolean bEnergyEconomy, boolean bStart) {
    if (context == null)
        return;//from www . ja va  2 s  .c o m
    Log.d(TAG, "Schedule Next Update for tracker " + bStart);
    if (bStart == false)
        return;
    Intent intent = new Intent(action);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // The update frequency should often be user configurable.  This is not.

    long currentTimeMillis = System.currentTimeMillis();
    long nextUpdateTimeMillis = currentTimeMillis + nMinTimeBetweenSend;
    Time nextUpdateTime = new Time();
    nextUpdateTime.set(nextUpdateTimeMillis);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    if (bEnergyEconomy)
        alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
    else
        alarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis, pendingIntent);
}

From source file:com.nextgis.mobile.TrackerService.java

protected void ScheduleNextUpdate(Context context, String action, long nMinTimeBetweenSend,
        boolean bEnergyEconomy, boolean bStart) {
    if (context == null)
        return;/*from ww w .  ja  v  a 2  s.  co m*/
    Log.d(MainActivity.TAG, "Schedule Next Update for tracker " + bStart);
    if (bStart == false)
        return;
    Intent intent = new Intent(action);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // The update frequency should often be user configurable.  This is not.

    long currentTimeMillis = System.currentTimeMillis();
    long nextUpdateTimeMillis = currentTimeMillis + nMinTimeBetweenSend;
    Time nextUpdateTime = new Time();
    nextUpdateTime.set(nextUpdateTimeMillis);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    if (bEnergyEconomy)
        alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
    else
        alarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis, pendingIntent);
}

From source file:com.jogden.spunkycharts.traditionalchart.TraditionalChartFragmentAdapter.java

public TraditionalChartFragmentAdapter(Context context, Handler handler, LocalBroadcastManager broadcastManager,
        TraditionalChartPanel priceChartPanel, LinearLayout timeAxisLayout, LinearLayout priceAxisLayout,
        TraditionalChartPanel volumeChartPanel, LinearLayout volumeAxisLayout, ViewGroup fragmentViewGroup,
        int priceSegmentWidth, TraditionalChartPreferences.Type chartType,
        TraditionalChartPreferences.Frequency chartFrequency, Cursor cursor, String symbol, Boolean... bArgs) {
    this._cntxt = context;
    this._guiThrdHndlr = handler;
    this._localBcastMngr = broadcastManager;
    this._priceSgmnt = priceChartPanel;
    this._timeAxis = timeAxisLayout;
    this._priceAxis = priceAxisLayout;
    this._volumeSgmnt = volumeChartPanel;
    this._volumeAxis = volumeAxisLayout;
    this._myContainer = fragmentViewGroup;
    this._priceSegWdth = priceSegmentWidth;
    this._chartType = chartType;
    this._chartFreq = chartFrequency;
    this._myCursor = cursor;
    this._updateTime = new Time();
    this._myResources = _cntxt.getResources();
    this._symbol = symbol;
    this._localBcastMngr.registerReceiver(new HighLowChange(), _rangeFltr);
    this._inflater = LayoutInflater.from(_cntxt);
    this._setCallbacks();
    this._setPricePanelDrawSemantics();
    this._volumeSgmnt.setDrawSemantics(DrawSemantics_SILO.class);
    if (_myCursor != null)
        this._init();
}

From source file:co.carlosjimenez.android.currencyalerts.app.DetailActivityFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    if (data == null) {
        Log.d(LOG_TAG, "Detail Forex Loader Finished: No data returned");

        return;//from w  ww.jav  a 2s  .  c  o m
    }
    if (!data.moveToFirst()) {
        Log.d(LOG_TAG, "Detail Forex Loader Finished: No data returned");

        data.close();
        return;
    }

    long lDate = 0;
    String sDate = "";
    String sCurrency = "";
    int i = 0;
    double dRateAverage = 0;
    double dVal = 0;
    double dMinVal = 0;
    double dMaxVal = 0;

    data.moveToPosition(0);

    mCurrencyFromId = data.getString(COL_CURRENCY_FROM_ID);
    String currencyFromName = data.getString(COL_CURRENCY_FROM_NAME);
    String currencyFromSymbol = data.getString(COL_CURRENCY_FROM_SYMBOL);
    String countryFromName = data.getString(COL_COUNTRY_FROM_NAME);
    double currencyFromRate = ForexContract.RateEntry.getRateFromUri(mUri);

    mCurrencyToId = data.getString(COL_CURRENCY_TO_ID);
    String currencyToName = data.getString(COL_CURRENCY_TO_NAME);
    String currencyToSymbol = data.getString(COL_CURRENCY_TO_SYMBOL);
    String countryToName = data.getString(COL_COUNTRY_TO_NAME);
    double currencyToRate = ForexContract.RateEntry.getRateFromUri(mUri) * data.getDouble(COL_RATE_VAL);

    Glide.with(getActivity()).load(data.getString(COL_COUNTRY_FROM_FLAG)).error(R.drawable.globe).crossFade()
            .into(mIvFlagFrom);
    mIvFlagFrom.setContentDescription(Utility.formatCountryFlagName(mContext, countryFromName));

    Glide.with(getActivity()).load(data.getString(COL_COUNTRY_TO_FLAG)).error(R.drawable.globe).crossFade()
            .into(mIvFlagTo);
    mIvFlagFrom.setContentDescription(Utility.formatCountryFlagName(mContext, countryToName));

    mTvCurrencyFromDesc.setText(currencyFromName);
    mTvCurrencyFromDesc.setContentDescription(currencyFromName);

    mTvCurrencyFromRate
            .setText(Utility.formatCurrencyRate(getActivity(), currencyFromSymbol, currencyFromRate));
    mTvCurrencyFromRate.setContentDescription(String.valueOf(currencyFromRate) + " " + currencyFromName);

    mTvCurrencyToDesc.setText(currencyToName);
    mTvCurrencyToDesc.setContentDescription(currencyToName);

    mTvCurrencyToRate.setText(Utility.formatCurrencyRate(getActivity(), currencyToSymbol, currencyToRate));
    mTvCurrencyToRate.setContentDescription(String.valueOf(currencyToRate) + " " + currencyToName);

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

    int julianDate = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

    dayTime = new Time();
    long lMinDate = dayTime.setJulianDay(julianDate - DEFAULT_DAYS_FOREX_AVERAGE);

    sDate = Utility.getDateString(getActivity(), data.getLong(COL_RATE_DATE));

    for (i = 0; i < data.getCount() && i < DEFAULT_DAYS_FOREX_AVERAGE; i++) {
        data.moveToPosition(i);

        lDate = data.getLong(COL_RATE_DATE);
        if (lDate < lMinDate) {
            break;
        }

        sCurrency = data.getString(COL_CURRENCY_TO_ID);
        sDate = Utility.getDateString(getActivity(), lDate);
        dVal = data.getDouble(COL_RATE_VAL);
        dRateAverage += dVal;

        if (i == 0) {
            dMinVal = dVal;
            dMaxVal = dVal;
        } else {
            dMinVal = dMinVal < dVal ? dMinVal : dVal;
            dMaxVal = dMaxVal > dVal ? dMaxVal : dVal;
        }
    }
    dRateAverage = dRateAverage / i;

    if (data.getCount() > 1)
        mTvPeriod.setText(data.getCount() + " days");
    else
        mTvPeriod.setText(data.getCount() + " day");
    mTvMaxRate.setContentDescription(mTvPeriod.getText());

    mTvMaxRate.setText(
            Utility.formatCurrencyRate(getActivity(), data.getString(COL_CURRENCY_TO_SYMBOL), dMaxVal));
    mTvMaxRate.setContentDescription(mTvMaxRate.getText());

    mTvMinRate.setText(
            Utility.formatCurrencyRate(getActivity(), data.getString(COL_CURRENCY_TO_SYMBOL), dMinVal));
    mTvMinRate.setContentDescription(mTvMinRate.getText());

    mTvAverageRate.setText(
            Utility.formatCurrencyRate(getActivity(), data.getString(COL_CURRENCY_TO_SYMBOL), dRateAverage));
    mTvAverageRate.setContentDescription(mTvAverageRate.getText());

    // String text to share if user clicks on share menu icon
    mDisplayedRate = String.format("%s - %s %s = %s %s", sDate, currencyFromRate, mCurrencyFromId,
            currencyToRate, mCurrencyToId);
    mDisplayedCurrencyIds = mCurrencyFromId + "-" + mCurrencyToId;
    mDisplayedCurrencyNames = currencyToName;

    mContext.supportStartPostponedEnterTransition();

    if (null != mToolbar) {
        Menu menu = mToolbar.getMenu();
        if (null != menu)
            menu.clear();
        mToolbar.inflateMenu(R.menu.detailfragment);
        finishCreatingMenu(mToolbar.getMenu());
    }
}

From source file:dk.larsbak.sunshine.ForecastFragment.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./*from   w  w w. ja  v a 2 s  .c om*/
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException {

    // These are the names of the JSON objects that need to be extracted.
    final String OWM_LIST = "list";
    final String OWM_WEATHER = "weather";
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";
    final String OWM_DESCRIPTION = "main";

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

    // 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();

    String[] resultStrs = new String[numDays];

    // Data is fetched in Celsius by default.
    // If user prefers to see in Fahrenheit, convert the values here.
    // We do this rather than fetching in Fahrenheit so that the user can
    // change this option without us having to re-fetch the data once
    // we start storing the values in a database.
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    String unitType = sharedPrefs.getString(getString(R.string.pref_units_key),
            getString(R.string.pref_units_metric));

    for (int i = 0; i < weatherArray.length(); i++) {
        // For now, using the format "Day, description, hi/low"
        String day;
        String description;
        String highAndLow;

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

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        long dateTime;
        // Cheating to convert this to UTC time, which is what we want anyhow
        dateTime = dayTime.setJulianDay(julianStartDay + i);
        day = getReadableDateString(dateTime);

        // description is in a child array called "weather", which is 1 element long.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);

        // 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);
        double high = temperatureObject.getDouble(OWM_MAX);
        double low = temperatureObject.getDouble(OWM_MIN);

        highAndLow = formatHighLows(high, low, unitType);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    for (String s : resultStrs) {
        Log.v(LOG_TAG, "Forecast entry: " + s);
    }
    return resultStrs;

}

From source file:com.jogden.spunkycharts.pricebyvolumechart.PriceByVolumeChartFragmentAdapter.java

@Override
public void bridge(DataClientInterface dataClient, DataConsumerInterface.InsertCallback iCallback) {
    _updateReady.set(false);//from   w ww.  j  a va2s  . c  o  m
    iCallback.clear(_symbol, (DataConsumerInterface) this);

    Pair<OHLC[], Time> pricePair = dataClient.getBulk(_symbol, null, DataClientLocalDebug.DATA_PRICE_DEF);
    Pair<Integer[], Time> volPair = dataClient.getBulk(_symbol, null, DataClientLocalDebug.DATA_VOL_DEF);

    final OHLC[] prices = pricePair.first;
    final Integer[] vols = volPair.first;
    int len = vols.length;
    if (prices.length != len)
        throw new IllegalStateException("price / volume getBulk size inconconsistency");

    _updateTime.set(pricePair.second);
    --len;
    long endMs = _updateTime.toMillis(true);
    endMs /= GMS;
    endMs *= GMS;
    List<ContentValues> valsList = new ArrayList<ContentValues>();
    Time t = new Time();
    for (int i = 0; i < len; ++i) {
        t.set(endMs - ((len - i) * GMS));
        valsList.add(_createContentValues(prices[i], vols[i], t));
        /*Log.d("Data-Consumer-Get-Bulk", 
           prices[i].toString() +"   " +
           String.valueOf(vols[i]) + "   " + 
           t.format("%H:%M:%S")); */
    }

    OHLC price = prices[len];
    _lastGranularPriceSeg = new OHLC(price);
    _lastGranularVolSeg = vols[len];
    _lastGranularSegTime.set(endMs);
    _updateReady.set(true);

    iCallback.insertRows(valsList, _symbol, (DataConsumerInterface) this);

}

From source file:com.markupartist.sthlmtraveling.RoutesActivity.java

private JourneyQuery getJourneyQueryFromUri(Uri uri) {
    JourneyQuery jq = new JourneyQuery();

    jq.origin = new Planner.Location();
    jq.origin.name = uri.getQueryParameter("start_point");
    if (!TextUtils.isEmpty(uri.getQueryParameter("start_point_id"))) {
        jq.origin.id = Integer.parseInt(uri.getQueryParameter("start_point_id"));
    }/*from  ww w  . j av a2  s.  c om*/
    if (!TextUtils.isEmpty(uri.getQueryParameter("start_point_lat"))
            && !TextUtils.isEmpty(uri.getQueryParameter("start_point_lng"))) {
        jq.origin.latitude = (int) (Double.parseDouble(uri.getQueryParameter("start_point_lat")) * 1E6);
        jq.origin.longitude = (int) (Double.parseDouble(uri.getQueryParameter("start_point_lng")) * 1E6);
    }

    jq.destination = new Planner.Location();
    jq.destination.name = uri.getQueryParameter("end_point");
    if (!TextUtils.isEmpty(uri.getQueryParameter("end_point_id"))) {
        jq.destination.id = Integer.parseInt(uri.getQueryParameter("end_point_id"));
    }
    if (!TextUtils.isEmpty(uri.getQueryParameter("end_point_lat"))
            && !TextUtils.isEmpty(uri.getQueryParameter("end_point_lng"))) {
        jq.destination.latitude = (int) (Double.parseDouble(uri.getQueryParameter("end_point_lat")) * 1E6);
        jq.destination.longitude = (int) (Double.parseDouble(uri.getQueryParameter("end_point_lng")) * 1E6);
    }

    jq.isTimeDeparture = true;
    if (!TextUtils.isEmpty(uri.getQueryParameter("isTimeDeparture"))) {
        jq.isTimeDeparture = Boolean.parseBoolean(uri.getQueryParameter("isTimeDeparture"));
    }

    jq.time = new Time();
    String timeString = uri.getQueryParameter("time");
    if (!TextUtils.isEmpty(timeString)) {
        jq.time.parse(timeString);
    } else {
        jq.time.setToNow();
    }

    return jq;
}

From source file:org.apache.cordova.globalization.Globalization.java

private JSONObject getStringtoDate(JSONArray options) throws GlobalizationError {
    JSONObject obj = new JSONObject();
    Date date;/*from w w w  . ja  v  a2s  .c  o  m*/
    try {
        //get format pattern from android device (Will only have device specific formatting for short form of date) or options supplied
        DateFormat fmt = new SimpleDateFormat(getDatePattern(options).getString("pattern"));

        //attempt parsing string based on user preferences
        date = fmt.parse(options.getJSONObject(0).get(DATESTRING).toString());

        //set Android Time object
        Time time = new Time();
        time.set(date.getTime());

        //return properties;
        obj.put("year", time.year);
        obj.put("month", time.month);
        obj.put("day", time.monthDay);
        obj.put("hour", time.hour);
        obj.put("minute", time.minute);
        obj.put("second", time.second);
        obj.put("millisecond", Long.valueOf(0));
        return obj;
    } catch (Exception ge) {
        throw new GlobalizationError(GlobalizationError.PARSING_ERROR);
    }
}

From source file:com.dgsd.android.ShiftTracker.Fragment.EditShiftFragment.java

private void prepopulate() {
    if (mInitialShift != null) {
        mName.setText(mInitialShift.name);
        mNotes.setText(mInitialShift.note);
        mSaveAsTemplate.setChecked(mInitialShift.isTemplate);
        if (mInitialShift.julianDay >= 0)
            onDateSelected(TYPE_CODE_START, mInitialShift.julianDay);

        if (mInitialShift.endJulianDay >= 0)
            onDateSelected(TYPE_CODE_END, mInitialShift.endJulianDay);

        if (mInitialShift.getStartTime() != -1)
            setStartTime(mInitialShift.getStartTime());

        if (mInitialShift.getEndTime() != -1)
            setEndTime(mInitialShift.getEndTime());

        if (mInitialShift.breakDuration >= 0)
            mUnpaidBreak.setText(String.valueOf(mInitialShift.breakDuration));

        if (mInitialShift.payRate >= 0)
            mPayRate.setText(String.valueOf(mInitialShift.payRate));

        for (int i = 0, len = mRemindersValues.length; i < len; i++) {
            if (String.valueOf(mInitialShift.reminder).equals(mRemindersValues[i])) {
                setSelection(mReminders, i);
                break;
            }/*ww  w. ja  va2 s .com*/
        }

        getSherlockActivity().invalidateOptionsMenu();
    } else {
        //No initial shift, just set up our date/time values
        final int jd = mInitialJulianDay < 0 ? TimeUtils.getCurrentJulianDay() : mInitialJulianDay;
        onDateSelected(TYPE_CODE_START, jd);
        onDateSelected(TYPE_CODE_END, jd);

        //Default 9 - 5 shift
        Time t = new Time();
        t.setToNow();
        t.hour = 9;
        t.minute = 0;
        t.second = 0;
        t.normalize(true);

        final Prefs p = Prefs.getInstance(getActivity());
        setStartTime(p.get(getString(R.string.settings_key_default_start_time), t.toMillis(true)));

        t.hour = 17;
        t.normalize(true);

        setEndTime(p.get(getString(R.string.settings_key_default_end_time), t.toMillis(true)));

        mUnpaidBreak.setText(p.get(getString(R.string.settings_key_default_break_duration), null));
        mPayRate.setText(p.get(getString(R.string.settings_key_default_pay_rate), null));

        String remindersVal = p.get(getString(R.string.settings_key_default_reminder), "None");
        int index = 0;
        for (int i = 0, len = mRemindersLabels.length; i < len; i++) {
            if (TextUtils.equals(remindersVal, mRemindersLabels[i])) {
                index = i;
                break;
            }
        }

        setSelection(mReminders, index);
    }
}