Example usage for android.text.format DateUtils DAY_IN_MILLIS

List of usage examples for android.text.format DateUtils DAY_IN_MILLIS

Introduction

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

Prototype

long DAY_IN_MILLIS

To view the source code for android.text.format DateUtils DAY_IN_MILLIS.

Click Source Link

Usage

From source file:com.example.android.sunshine.sync.SunshineSyncTask.java

/**
 * Performs the network request for updated weather, parses the JSON from that request, and
 * inserts the new weather information into our ContentProvider. Will notify the user that new
 * weather has been loaded if the user hasn't been notified of the weather within the last day
 * AND they haven't disabled notifications in the preferences screen.
 *
 * @param context Used to access utility methods and the ContentResolver
 *///from  w  w w. j av  a 2  s. com
synchronized public static void syncWeather(Context context) {

    try {
        /*
         * The getUrl method will return the URL that we need to get the forecast JSON for the
         * weather. It will decide whether to create a URL based off of the latitude and
         * longitude or off of a simple location as a String.
         */
        URL weatherRequestUrl = NetworkUtils.getUrl(context);

        /* Use the URL to retrieve the JSON */
        String jsonWeatherResponse = NetworkUtils.getResponseFromHttpUrl(weatherRequestUrl);

        /* Parse the JSON into a list of weather values */
        ContentValues[] weatherValues = OpenWeatherJsonUtils.getWeatherContentValuesFromJson(context,
                jsonWeatherResponse);

        /*
         * In cases where our JSON contained an error code, getWeatherContentValuesFromJson
         * would have returned null. We need to check for those cases here to prevent any
         * NullPointerExceptions being thrown. We also have no reason to insert fresh data if
         * there isn't any to insert.
         */
        if (weatherValues != null && weatherValues.length != 0) {
            /* Get a handle on the ContentResolver to delete and insert data */
            ContentResolver sunshineContentResolver = context.getContentResolver();

            /* Delete old weather data because we don't need to keep multiple days' data */
            sunshineContentResolver.delete(WeatherContract.WeatherEntry.CONTENT_URI, null, null);

            /* Insert our new weather data into Sunshine's ContentProvider */
            sunshineContentResolver.bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, weatherValues);

            /*
             * Finally, after we insert data into the ContentProvider, determine whether or not
             * we should notify the user that the weather has been refreshed.
             */
            boolean notificationsEnabled = SunshinePreferences.areNotificationsEnabled(context);

            /*
             * If the last notification was shown was more than 1 day ago, we want to send
             * another notification to the user that the weather has been updated. Remember,
             * it's important that you shouldn't spam your users with notifications.
             */
            long timeSinceLastNotification = SunshinePreferences.getEllapsedTimeSinceLastNotification(context);

            boolean oneDayPassedSinceLastNotification = false;

            if (timeSinceLastNotification >= DateUtils.DAY_IN_MILLIS) {
                oneDayPassedSinceLastNotification = true;
            }

            /*
             * We only want to show the notification if the user wants them shown and we
             * haven't shown a notification in the past day.
             */
            if (notificationsEnabled && oneDayPassedSinceLastNotification) {
                NotificationUtils.notifyUserOfNewWeather(context);
            }

            /* If the code reaches this point, we have successfully performed our sync */

        }

    } catch (Exception e) {
        /* Server probably invalid */
        e.printStackTrace();
    }

    // Sync new weather data to Android Wear
    sendWearWeatherData(context);

}

From source file:com.adkdevelopment.rssreader.data.services.FetchJobService.java

/**
 * Raises a notification each day on news update.
 *//*from ww  w .j  a  va 2  s.c  o m*/
private void sendNotification() {

    PrefsManager prefsManager = new PrefsManager(getBaseContext());

    Context context = getApplicationContext();
    final String NOTIFICATION_GROUP = "notif_group";
    final int NOTIFICATION_ID_1 = 101;

    if (prefsManager.receiveNotifications()) {
        //checking the last update and notify if it's the first of the day
        if (System.currentTimeMillis() - prefsManager.getLastNotification() >= DateUtils.DAY_IN_MILLIS) {

            Intent intent = new Intent(context, MainActivity.class);

            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, NOTIFICATION_ID_1, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

            builder.setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true)
                    .setContentTitle(context.getString(R.string.app_name))
                    .setContentText(context.getString(R.string.articles_notification))
                    .setContentIntent(pendingIntent).setSmallIcon(R.drawable.logo_title)
                    .setTicker(context.getString(R.string.app_name))
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(context.getString(R.string.articles_notification)))
                    .setGroup(NOTIFICATION_GROUP).setGroupSummary(true);

            NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
            managerCompat.notify(NOTIFICATION_ID_1, builder.build());

            prefsManager.setLastNotification();
        }

    }
}

From source file:android.support.v7.app.TwilightManager.java

private void updateState(@NonNull Location location) {
    final TwilightState state = sTwilightState;
    final long now = System.currentTimeMillis();
    final TwilightCalculator calculator = TwilightCalculator.getInstance();

    // calculate yesterday's twilight
    calculator.calculateTwilight(now - DateUtils.DAY_IN_MILLIS, location.getLatitude(),
            location.getLongitude());//  w w w .  j a v  a 2 s  .  c  o  m
    final long yesterdaySunset = calculator.sunset;

    // calculate today's twilight
    calculator.calculateTwilight(now, location.getLatitude(), location.getLongitude());
    final boolean isNight = (calculator.state == TwilightCalculator.NIGHT);
    final long todaySunrise = calculator.sunrise;
    final long todaySunset = calculator.sunset;

    // calculate tomorrow's twilight
    calculator.calculateTwilight(now + DateUtils.DAY_IN_MILLIS, location.getLatitude(),
            location.getLongitude());
    final long tomorrowSunrise = calculator.sunrise;

    // Set next update
    long nextUpdate = 0;
    if (todaySunrise == -1 || todaySunset == -1) {
        // In the case the day or night never ends the update is scheduled 12 hours later.
        nextUpdate = now + 12 * DateUtils.HOUR_IN_MILLIS;
    } else {
        if (now > todaySunset) {
            nextUpdate += tomorrowSunrise;
        } else if (now > todaySunrise) {
            nextUpdate += todaySunset;
        } else {
            nextUpdate += todaySunrise;
        }
        // add some extra time to be on the safe side.
        nextUpdate += DateUtils.MINUTE_IN_MILLIS;
    }

    // Update the twilight state
    state.isNight = isNight;
    state.yesterdaySunset = yesterdaySunset;
    state.todaySunrise = todaySunrise;
    state.todaySunset = todaySunset;
    state.tomorrowSunrise = tomorrowSunrise;
    state.nextUpdate = nextUpdate;
}

From source file:com.battlelancer.seriesguide.ui.BaseActivity.java

/**
 * Periodically do an automatic backup of the show database.
 *//*from   w  w w.  j  a v  a2s. com*/
private boolean onAutoBackup() {
    if (!AdvancedSettings.isAutoBackupEnabled(this)) {
        return false;
    }

    long now = System.currentTimeMillis();
    long previousBackupTime = AdvancedSettings.getLastAutoBackupTime(this);
    final boolean isTime = (now - previousBackupTime) > 7 * DateUtils.DAY_IN_MILLIS;

    if (isTime) {
        TaskManager.getInstance(this).tryBackupTask();
        return true;
    } else {
        return false;
    }
}

From source file:com.bubblegum.traceratops.app.ui.adapters.plugins.AbsAdapterPlugin.java

private String systemTimeInMillisToSystemDateFormat(Context context, long millis) {
    return DateUtils.getRelativeDateTimeString(context, millis, DateUtils.SECOND_IN_MILLIS,
            2 * DateUtils.DAY_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE).toString();
}

From source file:ro.expectations.expenses.ui.accounts.AccountsAdapter.java

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    mCursor.moveToPosition(position);/*www .j a va  2 s . com*/

    // Set the row background
    ListHelper.setItemBackground(mContext, holder.itemView, isItemSelected(position),
            holder.mAccountIconBackground, holder.mSelectedIconBackground);

    // Set the icon
    String type = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.TYPE));
    AccountType accountType = AccountType.valueOf(type);
    if (accountType == AccountType.CREDIT_CARD || accountType == AccountType.DEBIT_CARD) {
        String issuer = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.SUBTYPE));
        CardIssuer cardIssuer;
        if (issuer == null) {
            cardIssuer = CardIssuer.OTHER;
        } else {
            try {
                cardIssuer = CardIssuer.valueOf(issuer);
            } catch (final IllegalArgumentException ex) {
                cardIssuer = CardIssuer.OTHER;
            }
        }
        holder.mAccountIcon
                .setImageDrawable(DrawableHelper.tint(mContext, cardIssuer.iconId, R.color.colorWhite));
    } else if (accountType == AccountType.ELECTRONIC) {
        String paymentType = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.SUBTYPE));
        ElectronicPaymentType electronicPaymentType;
        if (paymentType == null) {
            electronicPaymentType = ElectronicPaymentType.OTHER;
        } else {
            try {
                electronicPaymentType = ElectronicPaymentType.valueOf(paymentType);
            } catch (IllegalArgumentException ex) {
                electronicPaymentType = ElectronicPaymentType.OTHER;
            }
        }
        holder.mAccountIcon.setImageDrawable(
                DrawableHelper.tint(mContext, electronicPaymentType.iconId, R.color.colorWhite));
    } else {
        holder.mAccountIcon
                .setImageDrawable(DrawableHelper.tint(mContext, accountType.iconId, R.color.colorWhite));
    }

    // Set the icon background color
    GradientDrawable bgShape = (GradientDrawable) holder.mAccountIconBackground.getBackground();
    bgShape.setColor(0xFF000000 | ContextCompat.getColor(mContext, accountType.colorId));

    // Set the description
    holder.mAccountDescription.setText(accountType.titleId);

    // Set the title
    String title = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.TITLE));
    holder.mAccountTitle.setText(title);

    // Set the date
    long now = System.currentTimeMillis();
    long lastTransactionAt = mCursor
            .getLong(mCursor.getColumnIndex(ExpensesContract.Accounts.LAST_TRANSACTION_AT));
    if (lastTransactionAt == 0) {
        lastTransactionAt = mCursor.getLong(mCursor.getColumnIndex(ExpensesContract.Accounts.CREATED_AT));
    }
    holder.mAccountLastTransactionAt
            .setText(DateUtils.getRelativeTimeSpanString(lastTransactionAt, now, DateUtils.DAY_IN_MILLIS));

    // Set the account balance
    double balance = NumberUtils.roundToTwoPlaces(
            mCursor.getLong(mCursor.getColumnIndex(ExpensesContract.Accounts.BALANCE)) / 100.0);
    String currencyCode = mCursor.getString(mCursor.getColumnIndex(ExpensesContract.Accounts.CURRENCY));
    Currency currency = Currency.getInstance(currencyCode);
    NumberFormat format = NumberFormat.getCurrencyInstance();
    format.setCurrency(currency);
    format.setMaximumFractionDigits(currency.getDefaultFractionDigits());
    holder.mAccountBalance.setText(format.format(balance));
    if (balance > 0) {
        holder.mAccountBalance.setTextColor(ContextCompat.getColor(mContext, R.color.colorGreen700));
    } else if (balance < 0) {
        holder.mAccountBalance.setTextColor(ContextCompat.getColor(mContext, R.color.colorRed700));
    }
}

From source file:net.peterkuterna.android.apps.devoxxfrsched.ui.StarredActivity.java

private void refreshPager() {
    final long currentTimeMillis = UIUtils.getCurrentTime(this);

    if (currentTimeMillis >= UIUtils.START_DAYS_IN_MILLIS[0]
            && currentTimeMillis < (UIUtils.START_DAYS_IN_MILLIS[UIUtils.NUMBER_DAYS - 1]
                    + DateUtils.DAY_IN_MILLIS)) {
        mDuringConference = true;//from   w  w  w . ja v  a 2  s.c om
    } else {
        mDuringConference = false;
    }

    mTabsContainer.setVisibility(mDuringConference ? View.VISIBLE : View.GONE);

    mViewPager.setAdapter(mAdapter);
    mTabs.setAdapter(mAdapter);
}

From source file:com.xandy.calendar.event.CreateEventDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Activity activity = getActivity();
    final LayoutInflater layoutInflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = layoutInflater.inflate(R.layout.create_event_dialog, null);

    mColor = view.findViewById(R.id.color);
    mCalendarName = (TextView) view.findViewById(R.id.calendar_name);
    mAccountName = (TextView) view.findViewById(R.id.account_name);

    mEventTitle = (EditText) view.findViewById(R.id.event_title);
    mEventTitle.addTextChangedListener(this);

    mDate = (TextView) view.findViewById(R.id.event_day);
    if (mDateString != null) {
        mDate.setText(mDateString);/*from  ww  w .  ja v a  2 s . c o m*/
    }

    mAlertDialog = new AlertDialog.Builder(activity).setTitle(R.string.new_event_dialog_label).setView(view)
            .setPositiveButton(R.string.create_event_dialog_save, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    createAllDayEvent();
                    dismiss();
                }
            }).setNeutralButton(R.string.edit_label, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mController.sendEventRelatedEventWithExtraWithTitleWithCalendarId(this,
                            EventType.CREATE_EVENT, -1, mDateInMillis, mDateInMillis + DateUtils.DAY_IN_MILLIS,
                            0, 0, CalendarController.EXTRA_CREATE_ALL_DAY, -1, mEventTitle.getText().toString(),
                            mCalendarId);
                    dismiss();
                }
            }).setNegativeButton(android.R.string.cancel, null).create();

    return mAlertDialog;
}

From source file:org.voidsink.anewjkuapp.fragment.CalendarFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // init range
    now = System.currentTimeMillis();
    then = now + 14 * DateUtils.DAY_IN_MILLIS;
}

From source file:piuk.blockchain.android.ui.BlockchainStateFragment.java

private void updateView() {
    final boolean showProgress;

    AbstractWalletActivity activity = (AbstractWalletActivity) this.getActivity();

    if (activity == null)
        return;//from w w  w  . j av a  2  s  .c  o m

    if (!activity.application.isInP2PFallbackMode()) {
        showProgress = false;
    } else if (download != BlockchainService.ACTION_BLOCKCHAIN_STATE_DOWNLOAD_OK) {
        showProgress = true;

        if ((download & BlockchainService.ACTION_BLOCKCHAIN_STATE_DOWNLOAD_STORAGE_PROBLEM) != 0)
            progressView.setText(R.string.blockchain_state_progress_problem_storage);
        else if ((download & BlockchainService.ACTION_BLOCKCHAIN_STATE_DOWNLOAD_NETWORK_PROBLEM) != 0)
            progressView.setText(R.string.blockchain_state_progress_problem_network);
    } else if (bestChainDate != null) {
        final long blockchainLag = System.currentTimeMillis() - bestChainDate.getTime();
        final boolean blockchainUptodate = blockchainLag < Constants.BLOCKCHAIN_UPTODATE_THRESHOLD_MS;

        showProgress = !blockchainUptodate;

        final String downloading = getString(R.string.blockchain_state_progress_downloading);
        final String stalled = getString(R.string.blockchain_state_progress_stalled);

        final String stalledText;
        if (blockchainLag < 2 * DateUtils.DAY_IN_MILLIS) {
            final long hours = blockchainLag / DateUtils.HOUR_IN_MILLIS;
            progressView.setText(getString(R.string.blockchain_state_progress_hours, downloading, hours));
            stalledText = getString(R.string.blockchain_state_progress_hours, stalled, hours);
        } else if (blockchainLag < 2 * DateUtils.WEEK_IN_MILLIS) {
            final long days = blockchainLag / DateUtils.DAY_IN_MILLIS;
            progressView.setText(getString(R.string.blockchain_state_progress_days, downloading, days));
            stalledText = getString(R.string.blockchain_state_progress_days, stalled, days);
        } else if (blockchainLag < 90 * DateUtils.DAY_IN_MILLIS) {
            final long weeks = blockchainLag / DateUtils.WEEK_IN_MILLIS;
            progressView.setText(getString(R.string.blockchain_state_progress_weeks, downloading, weeks));
            stalledText = getString(R.string.blockchain_state_progress_weeks, stalled, weeks);
        } else {
            final long months = blockchainLag / (30 * DateUtils.DAY_IN_MILLIS);
            progressView.setText(getString(R.string.blockchain_state_progress_months, downloading, months));
            stalledText = getString(R.string.blockchain_state_progress_months, stalled, months);
        }

        delayMessageHandler.removeCallbacksAndMessages(null);
        delayMessageHandler.postDelayed(new Runnable() {
            public void run() {
                progressView.setText(stalledText);
            }
        }, Constants.BLOCKCHAIN_DOWNLOAD_THRESHOLD_MS);
    } else {
        showProgress = false;
    }

    progressView.setVisibility(activity.application.isInP2PFallbackMode() ? View.VISIBLE : View.GONE);

    if (activity.application.isInP2PFallbackMode() && !showProgress) {
        progressView.setText(R.string.running_in_p2p_mode);
    }

    getView().setVisibility(activity.application.isInP2PFallbackMode() ? View.VISIBLE : View.GONE);

}